反应:状态不更新第一次点击 [英] React: state not updating on first click

查看:89
本文介绍了反应:状态不更新第一次点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理购物车示例.

I am working on a shopping cart sample.

每次单击时,我都将项目的对象添加到Cart数组中. 第一次单击添加购物车按钮时,它不会更新购物车,但是会第二次更新.

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.

尽管如此,当我单击渲染器的return语句中的viewCart按钮时,它会显示购物车中物品的准确数量. 请参阅下面的代码:

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:

我需要能够查看购物车中准确的物品数量,而无需单击viewCart按钮.这些产品来自本地JSON文件,因此我认为JSON文件的加载没有任何问题.

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>
    )
}

推荐答案

仅仅因为您没有在console.log中看到它并不意味着它不会正确呈现,这里的问题是setState异步,因此如果您立即进行console.log记录就不会看到它( console.log将在状态更新之前执行),但是如果您仍然想记录您的购物车,您可以这样做:

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在状态更新后接受一个函数作为回调.

setState accepts a function as a callback once the state has been updated.

这篇关于反应:状态不更新第一次点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆