我在减速器以下且在初始状态以下。 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;
}
}
答案 0 :(得分:1)
您正在传播test::some_variable
的对象。这是一个数组。因此,使用方括号并扩展学生数组-students
students: [...action.data.students]
答案 1 :(得分: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;