请先看这个问题here .我正在使用每个人都在使用的示例对象。
{
entities: {
plans: {
1: {title: 'A', exercises: [1, 2, 3]},
2: {title: 'B', exercises: [5, 6]}
},
exercises: {
1: {title: 'exe1'},
2: {title: 'exe2'},
3: {title: 'exe3'}
5: {title: 'exe5'}
6: {title: 'exe6'}
}
},
currentPlans: [1, 2]
}
当用户单击“删除练习”时,消息可能如下所示:
{type: "REMOVE_EXERCISE", payload: 2}
我是否需要遍历所有计划,然后遍历每个计划中的所有练习才能删除此项目?这将如何在 reducer 中完成?
最佳答案
选项 A
只需删除 exercise
并修改正在处理的代码 plans
与 undefined
一起工作对象也是如此(这两种方式都很方便)。 reducer 示例:
[REMOVE_EXERCISE]: (state, action) => {
const newState = {
...state
}
delete newState.entities.exercises[action.payload] // deletes property with key 2
return newState;
}
选项 B
删除练习并通过所有
plans
也删除引用。例子:[REMOVE_EXERCISE]: (state, action) => {
const newState = {
...state,
};
Object.keys(newState.entities.plans).map(planKey => {
const currentPlan = newState.entities.plans[planKey];
// Filters exercises array in single plan
currentPlan.exercises = currentPlan.exercises.filter(exercise => {
return exercise !== action.payload;
});
newState.entities.plans[planKey] = currentPlan;
});
delete newState.entities.exercises[action.payload];
return newState;
},
选择正确的选项取决于
plans
的大小- 当它增长到相当大的规模时,它可能会减慢此处理速度。在这种情况下,您可以在这部分代码上设置速度测试,实现选项 B 并查看它是否/何时会成为瓶颈。无论哪种方式,我都会更新消耗
plans
的代码要处理的数据 undefined
值在 exercises
.这可以在选择器中轻松完成。
关于redux - 从规范化的 redux 存储中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40055933/