我知道之前已经问过这个问题,但几乎所有人都在谈论OP直接改变状态,我试图避免使用像扩展运算符这样的技术(在对象和数组中)但是尽管如此我得到以下错误:
Uncaught Error: A state mutation was detected between dispatches, in the path `courses.0`. This may cause incorrect behavior. (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)
at invariant (eval at <anonymous> (bundle.js:922), <anonymous>:40:15)
at eval (eval at <anonymous> (bundle.js:3825), <anonymous>:50:36)
at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:14:16)
at dispatch (eval at <anonymous> (bundle.js:3853), <anonymous>:37:18)
at eval (eval at <anonymous> (bundle.js:1151), <anonymous>:63:5)
at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:11:18)
at Object.eval [as saveCourse] (eval at <anonymous> (bundle.js:3860), <anonymous>:4:12)
at Object.ManageCoursePage._this.saveCourse [as onSave] (eval at <anonymous> (bundle.js:2080), <anonymous>:134:27)
at CourseForm._this.onHandleSave (eval at <anonymous> (bundle.js:2052), <anonymous>:93:19)
at Object.ReactErrorUtils.invokeGuardedCallback (eval at <anonymous> (bundle.js:1301), <anonymous>:69:16)
我读了the article that the error points to,因为它建议我检查我是否在我的reducer中手动改变状态,我看不出那可能发生的地方:
const courseReducer = (state = initialState.courses, action) => {
switch (action.type) {
case types.LOAD_COURSE_SUCCESS:
return action.courses;
case types.CREATE_COURSE_SUCCESS:
//This action throw the error
debugger;
return [
...state,
Object.assign({}, action.course)
];
case types.UPDATE_COURSE_SUCCESS:
//This action throw the error
debugger;
return [
...state.filter(course => course.id !== action.course.id),
Object.assign({}, action.course)
];
case types.DELETE_COURSE_SUCCESS:
return [...state.filter(course => course.id !== action.courseId)];
default:
return state;
}
};
这里可以用来复制错误的a sandbox with part of the application,奇怪的是,只有在创建新课程或尝试编辑现有课程时才会发生这种情况(行为CREATE_COURSE_SUCCESS
和{{1}分别在我的UPDATE_COURSE_SUCCESS
)
我真的很感激,如果有人能帮我弄清楚哪里可能是这个错误的根源。
答案 0 :(得分:6)
问题是你在let today = Date()
print(" Date object : \(today)")
let format = DateFormatter()
format.dateFormat = "mm/dd/yy"
print(" Date to String : \(format.string(from: today)")
中的CoursesPage.js
内变异状态:
mapStateToProps
Array#sort
是就地操作,因此它通过对源数组进行排序来改变源数组。这意味着,let courses = state.courses.sort((c1, c2) =>
c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);
正在改变sort
,从而导致错误。而是在排序前复制state.courses
:
state.courses
上面使用spread syntax将元素分散到一个基本上克隆它的新数组中。这与Array#slice
相同。然后你可以这样排序:
[...state.courses]
这不会改变原始let courses = [...state.courses].sort((c1, c2) =>
c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);
并且不会抛出错误。
注意:还有一些地方可以直接改变state.courses
,例如this.state
的第32行:
ManageCoursePage.js
只改变组件构造函数中的this.state.errors = {}
对象。请改用this.state
。