【问题标题】:Better syntax to update nested objects on redux更好的语法来更新 redux 上的嵌套对象
【发布时间】:2018-05-15 23:34:54
【问题描述】:

给定如下的 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 这样的reducer 更新操作? (除了可能创建一些vars 来引用内部路径)

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      因此,您可以做两件事来帮助简化这一过程。我喜欢做的第一件事是将逻辑移出reducer,而只是传入一个值并将expandAbilities设置为action. expandAbilities

      第二个实际上是我们在工作中所做的事情。我们使用 immutableJS 并编写了一个 reducer 来处理我们所有的状态调用,因为您可以给它一个需要更新的状态部分的路径以及更新它的值,因此我们将其提取出来,现在很容易说dispatch(actions.update({path: ['report', 'content', 'interaction', 'expandAbilities'], value: '123' }))

      您甚至可以扩展它,这样您就可以传入需要更新的值列表,甚至可以围绕数据执行验证。

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 2019-10-10
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多