首页 > 解决方案 > React - 更新状态数组时对象中的唯一键被覆盖

问题描述

我有一个将商品添加到购物车的功能。单击按钮时,我正在尝试为新对象项生成唯一键。我是new Date().getTime()根据点击频率来做的。我在函数内部测试了 console.log,它unique_id为每个新对象生成不同的数字。当我尝试将现有的对象状态数组与新item对象组合时,问题就开始了。所有现有unique_id的 s 都会被覆盖到最新的unique_id. 我还在为状态数组使用 React useState 钩子。React 有点相关,因为状态数组不应该直接编辑,而是通过 setter 方法。

我尝试了.push, .concat, Array.from, 扩展运算符的组合,在函数内部和外部循环和分配变量。我知道这是一种pass-by-referencevspass-by-value情况,因为这些数组方法只是浅拷贝。

const [cart, setCart] = useState([])

const addItem = (item) => {
   let cartArr = cart
   item['unique_id'] = new Date().getTime()
   setCart([...cartArr, item])
}

预期的:

[
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696123},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696256},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377}
]

但得到:

[
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377}
]

标签: javascriptreactjsmultidimensional-arrayreferencejavascript-objects

解决方案


而不是推送数组中的值,您可以连接数组和对象,请参阅下面的代码供您参考

  const [cart, setCart] = useState([]);
  const addItem = item => {
    item["unique_id"] = new Date().getTime();
    setCart([...cart, item]);
  };

这是codesandbox演示


推荐阅读