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

标签 javascript reactjs redux javascript-objects object-property

#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]

关于javascript - 无法分配给对象的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66933795/

相关文章:

javascript - Sencha Touch 2布局: Fit inner content

javascript - 使用 jquery 的 Ajax 跨域请求

javascript - 使用 Javascript/jquery 在 <p> 标签后添加换行符

reactjs - 更改 React-Native-Material-Design 模块中按钮的背景颜色

javascript - Firebase云函数中的空传播错误

javascript - 两种不同的 API 调用——计算汇率

javascript - 如何访问 axios 加载的对象属性?

reactjs - 如何强制更新功能组件?

reactjs - 如何使用 React Redux Hooks 加载 Spinner

reactjs - 集成测试 - redux/react + nock.js