从规范化的redux商店中删除商品

tit*_*ito 8 redux normalizr

请先在这里看到这个问题.我正在使用每个人都在使用的这个示例对象.

{
  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]
}
Run Code Online (Sandbox Code Playgroud)

当用户单击"删除练习"时,消息可能如下所示:

{type: "REMOVE_EXERCISE", payload: 2}
Run Code Online (Sandbox Code Playgroud)

我是否需要遍历所有计划,然后是每个计划中的所有练习才能删除此项目?如何在减速机中完成?

Cor*_*nCZ 0

选项A

只需删除exercise并修改正在处理对象的代码plansundefined无论哪种方式这都很方便)。减速机示例:

[REMOVE_EXERCISE]: (state, action) => {
  const newState = {
    ...state  
  }
  delete newState.entities.exercises[action.payload] // deletes property with key 2
  return newState;
}
Run Code Online (Sandbox Code Playgroud)

选项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;
},
Run Code Online (Sandbox Code Playgroud)

选择正确的选项取决于大小plans- 当它增长到显着大小时,可能会减慢此处理速度。在这种情况下,您可以对这部分代码设置速度测试,实施选项 B 并查看是否/何时会成为瓶颈。

无论哪种方式,我都会更新使用plans数据来undefined处理exercises. 这可以在选择器中轻松完成。