我有一个带有update动作的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
}
在化简器中,逻辑是合并合并合并。这是因为不要丢失其余的对象数据。
我认为我可以对对象进行迭代直到找到要更新的属性,但是我想知道您是否可以通过其他方式来管理这种情况。
答案 0 :(得分:1)
根据Redux docs article on "Immutable Update Patterns",该方法是正确的。
如果手工操作很麻烦,建议您使用immer
immutable update library。另外,我们新的redux-starter-kit
package在内部使用沉浸器,使您可以使用更简单的不变更新逻辑来编写化简器。我鼓励您尝试一下。