【问题标题】:Update property value in nested array (redux state)更新嵌套数组中的属性值(redux 状态)
【发布时间】:2019-01-28 12:16:13
【问题描述】:

如何更新 redux 状态下的某个嵌套属性?

假设我只想更新下面对象中的“值”属性。我知道你不应该深度复制以前的状态,但是我如何只在数组的对象中更改数组中的对象的属性?

提前致谢!

market {
  shops: [
    {
      name: 'abc',
      items: [
        {
          name: 'item1',
          value: 40,
          id: '234rfds32'
        },
        {}
      ]
    },
    {},
    {}
  ]
}

类似于以下内容:

state = {
  ...state, 
  shops: [
    ...state.shops,
    shops[index].items = [
      ...shops[index].items,
    ]
  ]
};

【问题讨论】:

  • market.shops[0].items[0].value = 10 这是你要找的吗?
  • @AnkitAgarwal 感谢您的快速回复,但不,我更新了帖子以更清楚地说明我在寻找什么。我想只更改“值”属性来更新状态。

标签: javascript reactjs redux


【解决方案1】:

这样的事情会奏效。 (代码看起来很丑,虽然没有测试)

var shop =  state.shops[index];
var items = [...shop.items];
items[<index>].value = 'your value';
shop.items = items;
var shops = [...state.shops];
shops[index] = shop;

state = {
...state, 
shops 
};

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 2021-04-15
    • 2018-07-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2020-11-17
    • 2016-05-20
    相关资源
    最近更新 更多