javascript - 尝试从嵌套的 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;
}
}
解决方案
您正在为 传播对象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;
...
推荐阅读
- html - 机身右侧的空间用于放置小型设备
- join - 使用 _PARTITIONDATE 左连接
- javascript - 带有 and 的内联代码不起作用,但使用常规 if 有效
- python - PyZMQ req socket - 挂在 context.term()
- bison - Yacc 代码同时读取 IF 和 ELSE 语句
- regex - 如果正则表达式和字符串都是变量,如何在 perl 中使用正则表达式
- xpath - 当路径包含空间时如何使用 node.xpath 访问节点?
- javascript - i & 0xFF vs i % 256 带负数
- javascript - 在 Node.js (v10.9.0) 中排序元素返回错误的结果
- python - 如果我有每日值,如何使用 Pandas 计算累积的每周值总和?