【发布时间】:2019-12-19 16:01:32
【问题描述】:
我有一个将商品添加到购物车的功能。单击按钮时,我正在尝试为新对象项生成唯一键。我有new Date().getTime() 根据点击频率执行此操作。我在函数内部测试了console.log,它为每个新对象生成不同的unique_id 数字。当我尝试将现有的对象状态数组与新的 item 对象组合时,问题就开始了。所有现有的unique_ids 都被覆盖为最新的unique_id。我还在为状态数组使用 React useState 钩子。 React 有点相关,因为状态数组不应该直接编辑,而是通过 setter 方法。
我尝试了.push、.concat、Array.from、扩展运算符、循环和在函数内外分配变量的组合。我知道这是 pass-by-reference 与 pass-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}
]
【问题讨论】:
-
我能知道,
cartArr变量在哪里定义? -
我忘了包括作业:
let cartArr = cart -
你能尝试创建一个简单的 React sn-p 来重现这个问题吗?
-
这取决于您拨打
addItem()的频率。能否请您在addItem()函数中记录时间以隔离问题? -
这样做会使 state 的
cart属性不可变。let cartArr = [...cart]
标签: javascript reactjs multidimensional-array reference javascript-objects