redux - 从规范化的 redux 存储中删除项目

标签 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}

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

最佳答案

选项 A

只需删除 exercise并修改正在处理的代码 plansundefined 一起工作对象也是如此(这两种方式都很方便)。 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/

相关文章:

reactjs - React + Redux + Normalizr api 请求错误处理

javascript - 将架构从 Normalizr v2 转换为 v3 时遇到问题

javascript - 如何使用 Normalizr 来展平具有不同类型对象的数组?

javascript - Normalizr -如何用于基于属性的分组

reactjs - '(dispatch: Dispatch) => void' 类型的参数不可分配给 'AnyAction' 类型的参数

javascript - 如何动态呈现消息

javascript - React 状态获取 "corrupted"

react-native - 使用 Redux 工具包中的 createEntityAdapter 时如何将实体作为类组件中的数组获取?

reactjs - Normalizr + Redux - 更新单个实体的属性

javascript - 未定义“createPolyglotMiddleware”