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

时间:2016-10-15 06:48:15

标签: redux normalizr

请先查看此问题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}

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

1 个答案:

答案 0 :(得分:0)

选项A

只需删除exercise并修改处理plans的代码,使其也可以与undefined对象一起使用(这两种方法都可以方便使用)。减速器示例:

[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值。这可以在选择器中轻松完成。

相关问题