0

我有低于减速器和低于初始状态。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;
  }
}
4

2 回答 2

1

您正在为 传播对象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;
    ...
于 2020-05-09T05:38:49.727 回答
1

你做得很好,do not to mutate the state简单地说,不要改变prevState刚刚更新的状态。

主要错误是,您试图更改学生的状态,因为它以前是array类型,而在更新它时,您将其设置为object类型只是一个错字。请使用 [ ] 而不是 { }

const state = {
  id: 1,
  students: [
    {first: 1},
    {second: 2},
    {third: 3}
  ]
}

const action = {
  data: {
    students: [
      {fourth: 4}
    ]
  }
}

const updatedStudents = {
  ...action.data.students
}

console.log(state);
console.log(updatedStudents);

所以,在你的情况下->

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;
于 2020-05-09T05:45:17.247 回答