我有一个将商品添加到购物车的功能。我试图在单击按钮时为新对象项生成唯一键。我有 new Date().getTime()
根据点击频率执行此操作。我在函数内部测试了 console.log,它为每个新对象生成不同的 unique_id
数字。当我尝试将现有的对象状态数组与新的 item
对象组合时,问题就开始了。所有现有的 unique_id
都会被覆盖为最新的 unique_id
。我还对状态数组使用 React useState 钩子(Hook)。 React 有点相关,因为状态数组不应该直接编辑,而应该通过 setter 方法编辑。
我尝试了.push
、.concat
、Array.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]);
};
关于javascript - React - 更新状态数组时对象中的唯一键被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471938/