我有产品的上下文文件和状态文件。当我尝试在产品组件中使用该上下文时,它返回未定义的值
产品上下文.js
import { createContext } from "react";
const ProductContext = createContext();
export default ProductContext;
产品状态.js
import ProductContext from './productContext';
import { useState } from 'react';
const ProductState = (props) => {
const productsInitial = [
{
"_id": "63a4cc857f40d0063116be5f",
"user": "63a4cbfd7f40d0063116be5d",
"title": "Cassava",
"description": "On-demand sand castle construction expertise.",
"imgURL": "null",
"price": "30",
"__v": 0
},
{
"_id": "63a4ccad7f40d0063116be69",
"user": "63a4cbfd7f40d0063116be5d",
"title": "Soyabeans",
"description": "On-demand sand castle construction expertise.",
"imgURL": "null",
"price": "30",
"__v": 0
}
]
const [products, setProducts] = useState(productsInitial);
// console.log(products);
return (
<>
<ProductContext.Provider value={{ products, setProducts }}>
{props.children}
</ProductContext.Provider>
</>
)
}
export default ProductState;
产品组件.js(React组件)
import React, { useContext } from 'react';
import ProductContext from '../context/products/productContext';
import ProductItems from './ProductItems';
console.log(ProductContext);
const ProductComponent = () => {
const context = useContext(ProductContext);
const { products, setProducts } = context;
return (
<>
<div className="col-lg-4 ">
{products.map((product) => {
return <ProductItems product={products} />
})}
</div>
</>
)
}
export default ProductComponent;
这条线
const context = useContext(ProductContext);
在Products.js中组件返回未定义的值,因为ProductContext返回未定义的值
1条答案
按热度按时间js81xvg61#
使用上下文的组件必须使用
ProductState
组件 Package如果不知道在哪里添加
ProductState
,可以在入口点文件中添加。可以简化对象的分解