反应:第一次点击状态不更新

React: state not updating on first click

我正在制作购物车示例。

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

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

我需要能够在不单击 viewCart 按钮的情况下查看购物车中准确的商品数量。产品来自本地 JSON 文件,所以我认为加载 JSON 文件没有任何问题。

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 将在状态更新之前执行 ),但是如果你仍然想做日志您的购物车,您可以:

this.setState(
   { Cart: [...this.state.Cart, ProductsJSON[productKey]] },
   () => console.log(this.state.Cart)
)

setState 接受一个函数作为状态更新后的回调。

Arber 的解决方案很有意义,但当我尝试它时,它产生了一个控制台警告:

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().