I am trying to get some datas from child to parent. There is a way I usually do, and it totally works. But for one page I used:
<Link to={{
pathname: `/productBuy`,
state: { product, iconClick }
}}>
and when I send another prop from App.js to productBuy page, it's shown under product and it's undefined.
Codes from App.js :
const [productInformation, setProductInformation] = useState([]);
<Route path="/productBuy" render={props => <ProductBuy {...props} productInformation {productInformation} setProductInformation={setProductInformation} />} />
productBuy.js :
const ProductBuy = (productInfo, {productInformation,setProductInformation}) => {
return (
<div className="productBuy">
<div className="productBuyContainer">
<ProductLeft productInfo={productInfo.location.state} />
<ProductRight productInfo={productInfo.location.state} productInformation={productInformation} setProductInformation={setProductInformation}/>
</div>
</div>
);
}
When I console.log, my props are shown under product object as undefined. and when I invoke a function, an error appears: ProductRight.js:51 Uncaught TypeError: setProductInformation is not a function
Is there a way to solve this problem?
CodePudding user response:
First of all you're missing the =
after productInformation
in the render prop:
<ProductBuy {...props} productInformation={productInformation} setProductInformation={setProductInformation} />
And the second issue is that you're unpacking the props incorrectly. Both productInformation
and setProductInformation
are available in the props
argument (the first positional argument) in your function, but you're unpacking it in the second argument instead:
// INCORRECT
const ProductBuy = (productInfo, {productInformation,setProductInformation}) => { ... }
You can unpack it from the productInfo
argument, which is an object that holds all the props:
const ProductBuy = (productInfo) => {
const { productInformation, setProductInformation } = productInfo;
return (
<div className="productBuy">
<div className="productBuyContainer">
<ProductLeft productInfo={productInfo.location.state} />
<ProductRight productInfo={productInfo.location.state} productInformation={productInformation} setProductInformation={setProductInformation}/>
</div>
</div>
);
}
You can also choose to unpack it at the top level:
const ProductBuy = ({ location, productInformation, setProductInformation }) => {
return (
<div className="productBuy">
<div className="productBuyContainer">
<ProductLeft productInfo={location.state} />
<ProductRight productInfo={location.state} productInformation={productInformation} setProductInformation={setProductInformation}/>
</div>
</div>
);
}
CodePudding user response:
Add equal sign when passing the productInformation
to props seems you forgot that in App.js
<Route path="/productBuy" render={props => <ProductBuy {...props} productInformation={productInformation} setProductInformation={setProductInformation} />} />