React: state not updating on first click

旧街凉风 提交于 2019-12-25 00:18:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!