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

问题描述

#interestingProblem 谁能解释一下,拜托? 我在更新第一个代码块中的状态时遇到了问题,但是当我像下面的第二个代码块中那样更新状态时没有问题。

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

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 可能是只读对象。在第二个代码块上,扩展运算符将键值对传递给新对象。

,

因为我假设在 React 中使用状态执行类似 **kwargs 时,您将一个非嵌套状态传递给一个具有嵌套状态的状态,将其重新分配为一个非嵌套状态,从而破坏了您的代码目标。