state
本地执行的逻辑移动到Redux中。这是将简单的React应用程序连接到Redux的第一步。您的应用程序的唯一功能是将用户的新消息添加到无序列表中。该示例很简单,以演示React和Redux如何协同工作。 ADD
。接下来,定义一个动作创建器addMessage()
,它创建添加消息的动作。您需要将message
给此操作创建者,并在返回的action
包含该消息。然后创建一个名为messageReducer()
的reducer来处理消息的状态。初始状态应该等于空数组。此reducer应向状态中保存的消息数组添加消息,或返回当前状态。最后,创建Redux存储并将其传递给reducer。 ADD
应该存在并保持一个等于字符串ADD
的值
testString: 'assert(ADD === "ADD", "The const ADD
should exist and hold a value equal to the string ADD
");'
- text: 动作创建者addMessage
应返回type
等于ADD
的对象,并且消息等于传入的消息。
testString: 'assert((function() { const addAction = addMessage("__TEST__MESSAGE__"); return addAction.type === ADD && addAction.message === "__TEST__MESSAGE__"; })(), "The action creator addMessage
should return an object with type
equal to ADD
and message equal to the message that is passed in.");'
- text: messageReducer
应该是一个函数。
testString: 'assert(typeof messageReducer === "function", "messageReducer
should be a function.");'
- text: 存储应该存在并且初始状态设置为空数组。
testString: 'assert((function() { const initialState = store.getState(); return typeof store === "object" && initialState.length === 0; })(), "The store should exist and have an initial state set to an empty array.");'
- text: 对商店调度addMessage
应该addMessage
向状态中保存的消息数组添加新消息。
testString: 'assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addMessage("__A__TEST__MESSAGE")); const addState = store.getState(); return (isFrozen && addState[0] === "__A__TEST__MESSAGE"); })(), "Dispatching addMessage
against the store should immutably add a new message to the array of messages held in state.");'
- text: 如果使用任何其他操作调用, messageReducer
应返回当前状态。
testString: 'assert((function() { const addState = store.getState(); store.dispatch({type: "FAKE_ACTION"}); const testState = store.getState(); return (addState === testState); })(), "The messageReducer
should return the current state if called with any other actions.");'
```