首页 > 解决方案 > 尝试从嵌套的 redux 对象中删除所有项目并添加传入项目

问题描述

我有低于减速器和低于初始状态。classinfo 是具有嵌套学生状态数组的父状态。使用下面的减速器,我计划(用新学生替换以前的学生)从以前的状态中删除所有学生,从“action.data.students”添加新学生并返回一个新状态。我第一次添加学生时没有问题,当我添加另一个学生时,我收到错误“在调度之间检测到状态突变”请告诉我,我做错了什么。

classInfo[ { Id:"", students:[] }]

function sampleReducer(state = initialState.classInfo, action) {
  switch (action.type) {
    case types.ADD_CLASSROOMS:
      return [...state, ...action.data];
    case types.REMOVE_CLASSROOMS:
      return state.filter((class) => class.id !== action.data);
    case types.ADD_STUDENT_DETAILS:
      const stateObj = state.map((class, i) => {
        if (class.id === action.data.id) {
          return {
            ...class,
            students: {
              ...action.data.students,
            },
          };
        }
        return {
          ...class,
        };


      });
      return stateObj;

    default:
      return state;
  }
}

标签: javascriptreactjsreduxreact-reduxredux-reducers

解决方案


您正在为 传播对象students。这是一个数组。所以使用方括号并展开学生数组 - students: [...action.data.students]

...
case types.ADD_STUDENT_DETAILS:
      const stateObj = state.map((class, i) => {
        if (class.id === action.data.id) {
          return {
            ...class,
            students: [ //<----use square brackets(as its an array)
              ...action.data.students
            ],
          };
        }
        return class;


      });
      return stateObj;
    ...

推荐阅读