javascript - 组件不使用消费者显示

标签 javascript reactjs

我使用 context api 正确地将数据传递给消费者, 但是产品组件不显示。

产品组件列表:

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;

我发送带有消费者值的数据的产品组件:

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;

提前谢谢您。

最佳答案

您没有从 Consumer 中返回映射数据,这就是您的 Product 组件未渲染的原因。在映射数据中添加 return 关键字即可正常工作

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

关于javascript - 组件不使用消费者显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55354326/

相关文章:

javascript - 将重复项组织到有序的单个数组中

javascript - 在 Swiper JS 中放大鼠标悬停

reactjs - 为什么 ref ='string' 是 "legacy"?

reactjs - 由于 docker build 中的 TypeScript 错误,npm run build 失败

javascript - React组件类变量访问

javascript - 单击时显示/隐藏 div

javascript - 闭包编译器 : Preserve function argument names?

Javascript Lossy PNG图像压缩库

javascript - 计算对 eval 的调用次数

javascript - react 设置具有特定类名的元素的最小高度属性