首页 > 解决方案 > 功能组件状态中的数组值未更新

问题描述

我已经设置了一个 useState 挂钩,如下所示。

  const [products, setProducts] = useState([
    {
      id: 1,
      qty: 0,
    },
    {
      id: 2,
      qty: 0,
    }
  ]);

我有一个 TouchOpacity 组件,它在按下时会触发以下功能。

 const _onPress = () => {
    const productArr = products;
    productArr[0].qty = value;
    setProducts(productArr);
  };

预期结果是 id 为 1 的产品必须将数量增加到 1,但这不会发生。

当我对来自状态的产品使用扩展运算符时,它按预期工作。

 const _onPress = () => {
    const productArr = [...products];
    productArr[0].qty = value;
    setProducts(productArr);
  };

这是什么原因?

标签: reactjsreact-native

解决方案


请注意,即使使用扩展运算符,在您的两个示例中,您都在改变状态。

如果您需要在状态或嵌套结构中使用数组,我强烈建议您尝试一个库,例如immer它可以简化事情,比重新创建对象更有效,并且总体上会给您一个很好的不改变状态的概念:

import produce from "immer";

const [products, setProducts] = useState([
  {
    id: 1,
    qty: 0,
  },
  {
    id: 2,
    qty: 0,
  }
]);

const _onPress = () => {
  setProducts(
    produce(products, draft => draft[0].qty = value)
  );
}

推荐阅读