interestingProblem有人能解释一下吗?🤔我在第一个代码块中更新状态时遇到了问题,但是当我在第二个代码块中更新状态时没有问题,如下所示。
我有个问题(无法分配给对象数量的只读属性)
const newItem = action.payload
newItem.quantity = 1
state.items = [...state.items, newItem]
我这样写代码的时候没有问题
const newItem = action.payload
state.items = [...state.items, { ...newItem, quantity: 1 }]
4条答案
按热度按时间332nm8kg1#
第一种方法是直接改变
action.payload
,因为你没有创建newItem
的副本,而是传递相同的引用。如果action.payload
是只读的,你会遇到这样的错误:第二种方法是可行的,因为你是从
action.payload
创建一个副本,而不是改变它:相反,您应该首先为您的工作方法创建一个副本:
slwdgvem2#
action.payload
可能是只读对象。在第二个代码块中,spread运算符将键值对传递给新对象。3zwjbxry3#
因为当在React中对状态做类似**kwargs的操作时,我假设,你正在将一个没有嵌套的状态传递到一个有嵌套状态的状态,将它重新分配到一个非嵌套状态,这破坏了你代码的目标。
70gysomp4#
这样可以解决问题
JavaScript有一个内置的函数来创建任何对象的深层副本。
还有
JavaScript中的Spread运算符不会创建对象的深层副本