首页 > 解决方案 > 更好的语法来更新 redux 上的嵌套对象

问题描述

给定一个 reducer 示例,如下所示

_({
  expandAbility: (state, a: { which: string }) => ({
    ...state,
    report: state.report && {
      waitingForIt: false,
      content: state.report.content && {
        ...state.report.content,
        interaction: {
          expandAbilities: !state.report.content.interaction.expandAbilities.contains(a.which)
            ? state.report.content.interaction.expandAbilities.add(a.which)
            : state.report.content.interaction.expandAbilities.remove(a.which)
        }
      }
    }
  }),
})

(下面给出的状态类型仅用于问题上下文目的)

const initialState = {
  report: undefined as
    | {
        waitingForIt?: boolean
        content?: {
          supportedFightIds: number[]
          deathCut: number
          reportInfo: any
          deathsFull: any
          deathsByPlayer: any
          deathsByAbility: any
          interaction: {
            expandAbilities: Set<string>
          }
        }
      }
    | undefined,
  error: undefined as Error | undefined
}

是否有任何技巧或“即时风味”库可以让我以expandAbility更短的方式编写减速器更新操作?(除了可能创建一些vars引用内部路径)

标签: reactjstypescriptredux

解决方案


有很多不可变的更新实用程序,请查看https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities上的一些选项,看看会发生什么成为最适合你的人。对于初学者,请查看 Immutability-helper 或 immer。


推荐阅读