reactjs - 更好的语法来更新 redux 上的嵌套对象

标签 reactjs typescript 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
}

是否有任何技巧或“当下 flavor ”库可以让我以更短的方式编写像 expandAbility 这样的 reducer 更新操作? (除了可能创建一些vars来引用内部路径)

最佳答案

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

关于reactjs - 更好的语法来更新 redux 上的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50360531/

相关文章:

javascript - 如何在 redux 中实现 'load more' 功能?

javascript - 传入数据和导出对象的最佳方式是什么?

html - 调整 MUI CircularProgress

reactjs - 从表单提交事件访问 typescript 中的 event.target.elements 属性

javascript - npm 脚本 Protractor 命令抛出错误

javascript - 如何在 Angular 2/Typescript 应用程序中使用第三方 js 库?

javascript - ReactJs Redux : how to dispatch an action on a user event and link actions with the reducers and the store

javascript - 从 .txt 文件读取并显示数据的 React 组件

reactjs - react : export const + export default vs export default

reactjs - 不变违规: requireNativeComponent: "FastImageView" was not found in the UIManager in react native