0

我正在尝试使用名为 onIncrement 的 onClick 来增加产品的数量。功能如下:

  const onIncrement = () => {
    setState({ ...state, quantity: (state.quantity) + 1 });
    props.productList(props.productData.price*(state.quantity + 1))
  };

我希望按钮在每次单击按钮时简单地向产品添加 +1。不幸的是,每次单击按钮时,此功能都会使数量增加一倍。有没有简单的方法来解决这个问题?我试着做:

  const onIncrement = () => {
    setState({ ...state, quantity: (state.quantity)/(state.quantity) + 1 });
    props.productList(props.productData.price*(state.quantity + 1))
  };

否定 state.quantity 的影响,只添加一个,但它不起作用。我在公式中遗漏了什么吗?谢谢

4

1 回答 1

0

由于setState是异步的,因此一旦调用该函数,状态更改就不会被触发。它将在后台更新。因此,始终建议使用setStateie 更新状态的功能方式,如下所示

 const onIncrement = () => {
    setState((state) => ({ ...state, quantity: (state.quantity) + 1 }));
 };

这样,当您尝试使用以前的状态进行更新时,总是会得到更新的状态。并且setState还接受第二个参数,即 a callback一旦状态更新,此回调将被触发,以便更新后的状态可供使用。有关更多信息,您可以参考react docs

因此,在您的情况下,如果您希望根据状态更新后的更新数量计算产品价格,那么您可以在上面讨论callbacksetState

const onIncrement = () => {
   setState((state) => ({ ...state, quantity: (state.quantity) + 1 }), () => {
      props.productList(props.productData.price*(state.quantity + 1))
   });
}

实际上,您的方案可以通过更简单的方式完成,如下所示

const onIncrement = () => {
    const updatedQuantity = state.quantity + 1
    setState(() => ({ ...state, quantity: updatedQuantity }));
    props.productList(props.productData.price*(updatedQuantity))
};

希望这可以帮助。

于 2020-07-01T03:51:25.950 回答