Component not displaying using consumer

问题: I correctly passed the data to the consumer using context api, however the product component doesn't display. Listofproducts component: import React, { Component } from...

问题:

I correctly passed the data to the consumer using context api, however the product component doesn't display.

Listofproducts component:

import React, { Component } from "react";
import Product from "./product";
import { Consumer } from "./context";

class Listofproducts extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }
  render() {
    return (
      <Consumer>
        {value => {
          value.map(data => {
            console.log(data); // its returning the data correctly
            return <Product key={data.id} product={data} />;
          });
        }}
      </Consumer>
    );
  }
}

export default Listofproducts;

Product component where i sent the data with the consumer value:

import React, { Component } from "react";

class Product extends Component {
  render() {
    console.log(this.props.product); // not showing anything on the console nor an error
    return <div>hello from product</div>;
  }
}

export default Product;

Thank you in advance.


回答1:

You aren't returning the mapped data from within the Consumer which is why your Product components are not getting rendered. Add a return keyword to mapped data and it will work correctly

<Consumer>
    {value => {
      return value.map(data => {
        console.log(data); 
        return <Product key={data.id} product={data} />;
      });
    }}
  </Consumer>

回答2:

You are not returning anything from the function given as child to Consumer.

Add the return keyword and it will work as expected.

class Listofproducts extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }
  render() {
    return (
      <Consumer>
        {value => {
          return value.map(data => {
            console.log(data); // its returning the data correctly
            return <Product key={data.id} product={data} />;
          });
        }}
      </Consumer>
    );
  }
}
  • 发表于 2019-03-27 14:25
  • 阅读 ( 161 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除