【问题标题】:Spread operator ES6 changing one field in an object in an array扩展运算符 ES6 更改数组中对象中的一个字段
【发布时间】:2018-02-21 11:32:33
【问题描述】:
case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const items = state.items
  items[index][name] = value
  return { ...state, items }

有没有一种简洁的方法可以使用扩展运算符来实现上面的代码?

【问题讨论】:

  • 不是答案,只是反馈。在 items[index][name] = value 中,您正在改变 redux 状态。不建议这样做。你会想先复制数组const item = [...state.items];然后用 ``items[index][name] = value` 变异就可以了;
  • 需要更多关于状态对象结构的信息

标签: javascript redux spread-syntax


【解决方案1】:

感谢您的 cmets。我的对象数组的结构如下,其中 items 数组中可以有很多对象。

items: [{
  name: '',
  code: '',
  quantity: '',
  netBottlePrice: '',
  netCasePrice: '',
  caseSize: '',
  volume: '',
  volumeUnit: '',
  amount: ''
}]

我找到了一种方法来完成更新 redux 状态而不使用扩展运算符对其进行变异:

case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const item = { ...state.items[index], [name]: value }
  const items = [...state.items.slice(0, index), item, ...state.items.slice(index +1) ]
  return { ...state, items }

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 2018-07-27
    • 2019-10-14
    • 2018-05-13
    • 1970-01-01
    • 2019-10-27
    • 2017-11-04
    • 2017-06-26
    • 2017-02-23
    相关资源
    最近更新 更多