javascript - React - 更新状态数组时对象中的唯一键被覆盖

标签 javascript reactjs multidimensional-array reference javascript-objects

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

我尝试了.push.concatArray.from、扩展运算符、内部和外部循环和赋值变量的组合功能。我知道这是一种按引用传递按值传递 的情况,因为这些数组方法只是浅拷贝。

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

最佳答案

您可以连接数组和对象,而不是将值推送到数组中,请参阅以下代码供您引用

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

这是codesandbox demo

关于javascript - React - 更新状态数组时对象中的唯一键被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471938/

相关文章:

javascript - 避免多次点击一个 div

Javascript 解析 http 响应时出错

reactjs - 如何使用 RouteComponentProps 测试 React 组件?

javascript - 在reactjs中创建并排div和响应式顶部底部div

PHP 多维数组 foreach

multidimensional-array - ndarray : Iterate over shuffled rows

JavaScript 错误 : SyntaxError: At least one digit must occur after a decimal point

javascript - 如何设置 JSONP?

javascript - 创建 react 应用程序错误: Cannot find module './locale'

javascript - 如何过滤仅包含数字的简单多维数组