const state = [
{
list: []
}
];
列表是学生对象的列表,例如:
list: [
{ id: 1, name: "Mark", attendance: true },
{ id: 2, name: "John", attendance: false }
]
我有一个按钮,可以触发对API的post请求,将出勤率更改为true。Post请求返回已更改的student对象,例如:
{ id: 2, name: "John", attendance: true }
这工作正常,如果没有错误,将调度
ATTENDANCE_SUCCESS
.
现在,在这种设置下:
export function students(state, action) {
let latestState = state[state.length - 1],
newState = Object.assign({}, latestState);
switch (action.type) {
case "ATTENDANCE_SUCCESS":
if (action.res.errorCode == 0) {
// Need to change redux state 'attendance' value to true for a student with ID returned from the POST request
}
}
const studentChanged = newState.list.find(function(student) {
return (
student.id ===
action.res.data.id
);
});
studentChanged.attendance = true;
但是它改变了redux商店中的状态(尽管我不确定它到底是如何发生的,因为我假设newState已经是一个副本)。
正确的方法是什么?