我正在使用React并使用上下文API,但不确定为什么我会收到此错误(可能只是某个地方出现了错字)。我在登录时正确传递了我的数据,但不确定为什么会收到此typeError
产品列表组件:
import React, { Component } from 'react'
import Product from './Product'
import Title from './Title'
import {ProductConsumer} from './Context'
import { storeProducts } from '../data'
export default class ProductList extends Component {
state = {
products: storeProducts
}
render() {
return (
<React.Fragment>
<div className="py-10 mx-auto">
<div className="Container">
<Title name="our" title=" Products" />
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />
})
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
)
}
}
产品组件 从“反应”导入React,{组件}
export default class Product extends Component {
render() {
return (
<div>
<h3>Hello from the Product </h3>
</div>
)
}
}
上下文API组件
import React, { Component } from 'react'
import Product from './Product';
import {storeProducts, detailProduct} from '../data'
const ProductContext = React.createContext();
//provider
//consumer
class ProductProvider extends Component {
state = {
product: storeProducts,
detailProduct: detailProduct
}
handleDetail = () => {
console.log('Hello from detail');
}
addToCart = () => {
console.log('Hello from add to cart');
}
render() {
return (
<ProductContext.Provider value={{
...this.state,
handleDetail:this.handleDetail,
addToCart:this.addToCart
}}>
{this.props.children}
</ProductContext.Provider>
)
}
}
const ProductConsumer = ProductContext.Consumer;
export {ProductProvider, ProductConsumer}