问题
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>
)
}
回答1:
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.
来源:https://stackoverflow.com/questions/49089636/react-state-not-updating-on-first-click