首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何改进reducer更新深度状态对象

如何改进reducer更新深度状态对象
EN

Stack Overflow用户
提问于 2018-12-05 04:10:44
回答 1查看 31关注 0票数 0

我有一个带有更新操作的reducer,工作得很好,但我想知道是否有改进代码的方法。

存储数据如下所示:

{
  test1: {
    name: 'test1',
    exercises: [
      {
        category: 'Hombro',
        name: 'Prensa de hombros',
        type: 'Peso y repeticiones',
        data: {
          weight: 10,
          reps: 3,
        },
      },
      {
        category: 'Hombro',
        name: 'Prensa de hombros con respaldo',
        type: 'Peso y repeticiones',
        data: {
          weight: 10,
          reps: 3,
        },
      },
    ],
  },
  test2: {
    name: 'test2',
    exercises: [],
  },
}

例如,更新单个练习的数据属性的策略如下:

const updateExerciseDataOfRoutine = (state, action) => {
  const { routineName, exerciseName, data } = action.payload

  return {
    ...state.routines,
    [routineName]: {
      ...state.routines[routineName],
      exercises: {
        ...state.routines[routineName].exercises,
        [exerciseName]: {
          ...state.routines[routineName].exercises[exerciseName],
          data,
        }
      }
    }
  }
}

const RoutinesReducer = (state = initialState, action) => {
if (action.type === DO_UPDATE_EXERCISE_DATA_OF_ROUTINE) {
    return {
      ...state,
      routines: updateExerciseDataOfRoutine(state, action),
    }
  }

  return state
}

在reducer中,逻辑是在merge上进行合并。这是为了不丢失剩余的对象数据。

我想我可以做一个函数来迭代对象,直到找到要更新的属性,但我想知道你是否用其他方式处理这种情况。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-05 04:27:35

根据Redux docs article on "Immutable Update Patterns"的说法,这种方法是正确的。

如果手工操作很痛苦,我们建议使用immer immutable update library。此外,我们的新redux-starter-kit package在内部使用immer,让您可以编写具有更简单的不可变更新逻辑的缩减程序。我鼓励你去尝试一下。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53620683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档