state 1
, state 2
, state 3
, state 4
, ...
等等,其中每个状态可能与最后一个状态相似,但每个状态是一个独特的数据。事实上,这种不变性提供了您可能听说过的时间旅行调试等功能。 Redux不会在其商店或减少者中主动强制执行状态不变性,而责任落在程序员身上。幸运的是,JavaScript(尤其是ES6)提供了一些有用的工具,可用于强制执行状态的不变性,无论是string
, number
, array
还是object
。请注意,字符串和数字是原始值,并且本质上是不可变的。换句话说,3总是3.您不能更改数字3的值。但是, array
或object
是可变的。实际上,您的状态可能包含array
或object
,因为它们是用于表示许多类型信息的有用数据结构。 store
和reducer
器,用于管理待办事项。完成在ADD_TO_DO
中写入ADD_TO_DO
情况,以向状态附加新的待办事项。使用标准JavaScript或ES6可以通过几种方法实现此目的。看看是否可以找到一种方法来返回一个新数组,其中action.todo
的项目附加到结尾。 todos
数组的状态进行初始化。
testString: 'assert((function() { const todos = [ "Go to the store", "Clean the house", "Cook dinner", "Learn to code" ]; const initialState = store.getState(); return Array.isArray(initialState) && initialState.join(",") === todos.join(","); })(), "The Redux store should exist and initialize with a state equal to the todos
array in the code editor.");'
- text: addToDo
和immutableReducer
都应该是函数。
testString: 'assert(typeof addToDo === "function" && typeof immutableReducer === "function", "addToDo
and immutableReducer
both should be functions.");'
- text: 在Redux存储上调度ADD_TO_DO
类型的操作应该添加todo
,不应该改变状态。
testString: 'assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addToDo("__TEST__TO__DO__")); const finalState = store.getState(); const expectedState = [ "Go to the store", "Clean the house", "Cook dinner", "Learn to code", "__TEST__TO__DO__" ]; return( isFrozen && DeepEqual(finalState, expectedState)); })(), "Dispatching an action of type ADD_TO_DO
on the Redux store should add a todo
item and should NOT mutate state.");'
```