redux 无法分配给对象的只读属性

w41d8nur  于 2023-06-06  发布在  其他
关注(0)|答案(4)|浏览(195)

interestingProblem有人能解释一下吗?🤔我在第一个代码块中更新状态时遇到了问题,但是当我在第二个代码块中更新状态时没有问题,如下所示。

我有个问题(无法分配给对象数量的只读属性)

const newItem = action.payload
newItem.quantity = 1
state.items = [...state.items, newItem]

我这样写代码的时候没有问题

const newItem = action.payload
state.items = [...state.items, { ...newItem, quantity: 1 }]
332nm8kg

332nm8kg1#

第一种方法是直接改变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]
slwdgvem

slwdgvem2#

action.payload可能是只读对象。在第二个代码块中,spread运算符将键值对传递给新对象。

3zwjbxry

3zwjbxry3#

因为当在React中对状态做类似**kwargs的操作时,我假设,你正在将一个没有嵌套的状态传递到一个有嵌套状态的状态,将它重新分配到一个非嵌套状态,这破坏了你代码的目标。

70gysomp

70gysomp4#

这样可以解决问题

const newItem = structuredClone(action.payload)
newItem.quantity = 1
state.items = [...state.items, newItem]

JavaScript有一个内置的函数来创建任何对象的深层副本。

const copiedObject = structuredClone(existingObject);

还有

const copiedObject = { ...existingObject }; //This doesn't create deep copy❌

JavaScript中的Spread运算符不会创建对象的深层副本

相关问题