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

Saa*_*aif 3 javascript javascript-objects object-property reactjs redux

#interestingProblem 任何人都可以解释一下,我在更新第一个代码块中的状态时遇到了问题,但是当我更新第二个代码块中的状态时没有问题,如下所示。

我遇到了问题:(无法分配给对象数量的只读属性)

const newItem = action.payload
newItem.quantity = 1
state.items = [...state.items, newItem]
Run Code Online (Sandbox Code Playgroud)

当我这样写代码时没有任何问题

const newItem = action.payload
state.items = [...state.items, { ...newItem, quantity: 1 }]
Run Code Online (Sandbox Code Playgroud)

buz*_*tto 6

您直接改变的第一种方法,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]
Run Code Online (Sandbox Code Playgroud)

第二种方法有效,因为您正在创建一个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 }]
Run Code Online (Sandbox Code Playgroud)

相反,您应该首先为您的工作方法创建一个副本:

// 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]
Run Code Online (Sandbox Code Playgroud)