我有一个带有更新操作的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上进行合并。这是为了不丢失剩余的对象数据。
我想我可以做一个函数来迭代对象,直到找到要更新的属性,但我想知道你是否用其他方式处理这种情况。
发布于 2018-12-05 04:27:35
根据Redux docs article on "Immutable Update Patterns"的说法,这种方法是正确的。
如果手工操作很痛苦,我们建议使用immer
immutable update library。此外,我们的新redux-starter-kit
package在内部使用immer,让您可以编写具有更简单的不可变更新逻辑的缩减程序。我鼓励你去尝试一下。
https://stackoverflow.com/questions/53620683
复制相似问题