Update a nested state in redux

2020-04-30 16:27发布

I have an object in my state as follows:

Exercise: {
    id: 1,
    question: '',
    type: '',
    Groups: [
      {
        id: 1,
        category: {
          id: 1,
          value: 'xxx',
          color: 'xxx'
        },
        groupParts: [
          {
            id: 1,
            Index: 7
          },
          {
            id: 2,
            Index: 11
          }
        ]
      }
    ]
  }

How can I update the value of the Index in id:2 in the reducer?

this is my last try which does not update the value, but creates another section in the current state:

case CURRENT_WORD_INDEX_UPDATED: 
  const index=action.selectedWordIndex
  return{...state,index:{...state.Groups[0].groupParts[1].index,in‌​dex},}

1条回答
倾城 Initia
2楼-- · 2020-04-30 16:58

you can make use of immutability-helper to update a nested state

import update from 'immutability-helper';

......

case CURRENT_WORD_INDEX_UPDATED: 
  const index=action.selectedWordIndex
  return update(state, {
      Groups: {
         0: {
             groupParts: {
               0: {
                 Index: {
                   $set: index
                 }
               }
             }
         }
      }
  })

查看更多
登录 后发表回答