I am working on a shopping cart sample.
On each click, I am adding an object of the project to the Cart array. When I click the add cart button the first time, it doesn't update the Cart, but it updates on the second time.
Although, when I click the viewCart button in the render's return statement, it shows the accurate number of items in the cart. See my code below:
I need to be able to see the accurate number of items in the cart without clicking the viewCart button. The products come from a local JSON file, so I don't think there is any problem with the loading of the JSON file.
constructor (props) {
super(props);
this.state = {
Cart: []
};
this.addItem = this.addItem.bind(this);
}
addItem(productKey) {
this.setState({ Cart: [...this.state.Cart, ProductsJSON[productKey]]})
console.log(this.state.Cart);
}
viewCart() {
console.log(this.state.Cart);
}
render() {
const AllProducts = ProductsJSON;
var Products = AllProducts.map((item) => {
return (
<div className="col-4" key={item.key} >
<a onClick={() => this.addItem(item.key)} className="btn btn-primary btn-sm">Add to Cart</a>
</div>
)
})
return (
<div className="container">
<div className="row">
{Products}
<a onClick={() => this.viewCart()} className="btn btn-primary btn-sm">viewCart</a>
</div>
</div>
)
}
Just because you don't see it in console.log
doesn't mean it will not render correctly, the problem here is that setState
is asynchronous , thus you will not see it if you console.log it right away ( console.log will execute before state is updated ), but if you still want to do log your cart, you can do:
this.setState(
{ Cart: [...this.state.Cart, ProductsJSON[productKey]] },
() => console.log(this.state.Cart)
)
setState accepts a function as a callback once the state has been updated.
Arber's solution makes sense but when I tried it, it produced a console warning saying:
State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.