how to use Immutability helper to update a nested

2020-01-31 12:14发布

问题:

Inside reducer, given a state object:

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

As you can see, the data is a nested array, with arrays in each of its elements.

Knowning that action.indexToUpdate will be a index for data, I want to update data[action.indexToUpdate].subset to a new array programmatically. For example, if action.indexToUpdate = 0, then data[0] will be updated from

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

to

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

In order to do so, I have:

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

But when I executed this, it returns error:

TypeError: value is undefined

on the update founction.

I have been looking at the react ducomentation here: https://facebook.github.io/react/docs/update.html but I couldn't really figure out how to do it. Please advise!

回答1:

Your update will look like

 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]
            }
          }
      }
  }
})

In case there are other fields in subset, but you only wish to the change the fields at specific index containing other keys, you would write

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