【问题标题】:how to use Immutability helper to update a nested object within an array?如何使用不变性助手更新数组中的嵌套对象?
【发布时间】:2017-06-16 09:44:42
【问题描述】:

在reducer内部,给定一个状态对象:

var state = {
        "data": [{
            "subset": [{
                "id": 1
            }, {
                "id": 2
            }]
        }, {
            "subset": [{
                "id": 10
            }, {
                "id": 11
            }, {
                "id": 12
            }]
        }]
    }

如您所见,数据是一个嵌套数组,每个元素中都有数组。

知道 action.indexToUpdate 将是数据的索引,我想以编程方式将 data[action.indexToUpdate].subset 更新为新数组。例如,如果 action.indexToUpdate = 0,则 data[0] 将从

[{"id":1},{"id":2}]

[{"id":4},{"id":5}]

为了做到这一点,我有:

let newSubset = [{"id":4},{"id":5}]
let newState = update(state.data[action.indexToUpdate], {
                subset: {
                    newSubset,
                },
            })

但是当我执行这个时,它返回错误:

TypeError: value is undefined

关于更新功能。

我一直在这里查看反应文档:https://facebook.github.io/react/docs/update.html,但我真的不知道该怎么做。请指教!

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您的更新将如下所示

     var obj = {"state" : {
        "data": [{
            "subset": [{
                "id": 1
            }, {
                "id": 2
            }]
        }, {
            "subset": [{
                "id": 10
            }, {
                "id": 11
            }, {
                "id": 12
            }]
        }]
    }}
    return update(obj, {
      "state" : {
          "data": {
              [action.indexToUpdate]: {
                "subset": {
                     $set: [newSubset]
                }
              }
          }
      }
    })
    

    如果子集中还有其他字段,但您只想更改包含其他键的特定索引处的字段,您可以编写

    return update(obj, {
      "state" : {
          "data": {
              [action.indexToUpdate]: {
                "subset": {
                    [id]: {$merge: newSubset}
                }
              }
          }
      }
    })
    

    【讨论】:

    • 感谢您的帮助!抱歉,我的问题过于简化了。我已经更新了问题 - 请看一下!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2022-09-23
    • 2021-02-06
    • 2023-01-12
    • 2023-01-23
    相关资源
    最近更新 更多