React Redux干净的方法来更新嵌套对象?

时间:2020-01-21 19:57:41

标签: reactjs redux

我有一个减速器,其初始状态看起来像这样:

const initialState = {
  person: {
    details: {
      addresses: {...},
      invoices: {...},
    },
    tasks: {
      option1: [...],
      option2: [...],
      option3: [...]
    }
  }
}

WAS 通过执行以下操作来更新化简器中的状态:

export const exampleReducer = (state = {...initialState}, action ) => {

  case actions.AN_ACTION:
    state.person.tasks.option1 = [new array]
    state.person.tasks.option2 = [another array]
    return state

  default:
    return state
}

但是引起我注意以下链接:https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns/,它建议您执行以下操作:

function updateVeryNestedField(state, action) {
  return {
    ...state,
    first: {
      ...state.first,
      second: {
        ...state.first.second,
        [action.someId]: {
          ...state.first.second[action.someId],
          fourth: action.someValue
        }
      }
    }
  }
}

有没有更整洁的方法来解决这个问题?

谢谢。

1 个答案:

答案 0 :(得分:2)

是的,您的示例代码正在改变现有状态。如该文档页面所示,您需要复制级嵌套数据,以创建正确的不可变更新。

这就是we strongly recommend using the Immer library for immutable updates(最好是our new official Redux Toolkit package的一部分)的原因之一。