【发布时间】:2022-01-06 03:20:10
【问题描述】:
我在我的 Cart.js 文件中使用了类组件,但它得到了“渲染不是函数”的错误。我也尝试将其更改为功能组件,但它也不起作用,请帮助我找到修复它的方法!非常感谢!
我的沙盒链接:https://codesandbox.io/s/why-cant-i-fetch-data-from-a-passed-value-forked-buz0u?file=/src/App.js
【问题讨论】:
我在我的 Cart.js 文件中使用了类组件,但它得到了“渲染不是函数”的错误。我也尝试将其更改为功能组件,但它也不起作用,请帮助我找到修复它的方法!非常感谢!
我的沙盒链接:https://codesandbox.io/s/why-cant-i-fetch-data-from-a-passed-value-forked-buz0u?file=/src/App.js
【问题讨论】:
Cart 组件有错误,因为您以不正确的方式使用来自ProductContext 的Consumer。改一下这段代码就可以解决问题了:
import React from "react";
const ProductContext = React.createContext();
export default class Cart extends React.Component {
render() {
return (
<div>
<ProductContext.Consumer>
{(value) => {
return <div>hello</div>
}}
</ProductContext.Consumer>
</div>
);
}
}
【讨论】:
const {cart} = value。你只需要使用{value}!
请更改您的购物车组件
import React from "react";
const ProductContext = React.createContext();
export default class Cart extends React.Component {
render() {
return (
<div>
<ProductContext.Provider value={null}>
hello
</ProductContext.Provider>
</div>
);
}
}
【讨论】: