[英]Angular 2 | cannot assign to array because it is a constant or a read-only property
[英]cannot assign to read-only property of object
#interestingProblem 任何人都可以解释一下,我在更新 state 时遇到了问题,就像在第一个代码块中一样,但是当我在第二个代码块中更新 state 时没有问题,如下所示。
我有一个问题:(不能分配给 object 数量的只读属性)
const newItem = action.payload
newItem.quantity = 1
state.items = [...state.items, newItem]
当我写这样的代码时我没有问题
const newItem = action.payload
state.items = [...state.items, { ...newItem, quantity: 1 }]
第一种方法是直接改变action.payload
,因为您没有创建到newItem
的副本,而是传递相同的引用。 鉴于action.payload
是只读的,您将面临错误:
// passing the same reference, 'newItem' points to 'action.payload'
// hence newItem is not copy
const newItem = action.payload
// here you mutate 'action.payload' since 'newItem' points to same reference
newItem.quantity = 1
state.items = [...state.items, newItem]
第二种方法有效,因为您正在从action.payload
创建副本而不是对其进行变异:
// here 'newItem' still points to same reference 'action.payload'
const newItem = action.payload
// but here you are spreading the values into a new object, not mutating directly
state.items = [...state.items, { ...newItem, quantity: 1 }]
相反,您应该首先为您的工作方法创建一个副本:
// here you create a new object from 'action.payload''action.payload'
// hence newItem contains the same values but it's a different object
const newItem = { ...action.payload }
// now you are not mutating 'action.payload', only 'newItem' that's a new object
newItem.quantity = 1
state.items = [...state.items, newItem]
action.payload
可能是只读的 object。 在第二个代码块上,扩展运算符将键值对传递给新的 object。
因为当我假设在 React 中使用 state 执行类似的 **kwargs 时,您将没有嵌套的 state 传递给具有嵌套 state 的目标,因为它声明了重新评估它的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.