mapDispatchToProps()
函数用于为React组件提供特定的操作创建器,以便它们可以针对Redux存储分派操作。它的结构与您在上一次挑战中编写的mapStateToProps()
函数类似。它返回一个对象,该对象将调度操作映射到属性名称,后者成为组件props
。但是,每个属性都返回一个函数,该函数使用动作创建者和任何相关的动作数据来调用dispatch
,而不是返回一个state
。您可以访问此dispatch
因为它在您定义函数时作为参数传递给mapDispatchToProps()
,就像您将state
传递给mapStateToProps()
。在幕后,阵营终极版使用终极版的store.dispatch()
进行这些分派mapDispatchToProps()
这类似于它将store.subscribe()
用于映射到state
组件。例如,您有一个loginUser()
动作创建者,它将username
作为动作有效负载。从mapDispatchToProps()
为此动作创建者返回的对象看起来像: {
submitLoginUser:function(username){
调度(loginUser(用户名));
}
}
addMessage()
的动作创建器。编写函数mapDispatchToProps()
,将dispatch
作为参数,然后返回一个对象。该对象应该将一个属性submitNewMessage
设置为dispatch函数,该函数在调度addMessage()
时为新消息添加一个参数。 addMessage
应该返回一个带有键type
和message
的对象。
testString: 'assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty("type") && addMessageTest.hasOwnProperty("message")); })(), "addMessage
should return an object with keys type
and message
.");'
- text: mapDispatchToProps
应该是一个函数。
testString: 'assert(typeof mapDispatchToProps === "function", "mapDispatchToProps
should be a function.");'
- text: mapDispatchToProps
应该返回一个对象。
testString: 'assert(typeof mapDispatchToProps() === "object", "mapDispatchToProps
should return an object.");'
- text: 使用submitNewMessage
的mapDispatchToProps
调度addMessage
应该向调度函数返回一条消息。
testString: 'assert((function() { let testAction; const dispatch = (fn) => { testAction = fn; }; let dispatchFn = mapDispatchToProps(dispatch); dispatchFn.submitNewMessage("__TEST__MESSAGE__"); return (testAction.type === "ADD" && testAction.message === "__TEST__MESSAGE__"); })(), "Dispatching addMessage
with submitNewMessage
from mapDispatchToProps
should return a message to the dispatch function.");'
```