--- id: 5a24c314108439a4d4036146 title: Map Dispatch to Props challengeType: 6 isRequired: false videoUrl: '' localeTitle: 将调度映射到道具 --- ## Description
mapDispatchToProps()函数用于为React组件提供特定的操作创建器,以便它们可以针对Redux存储分派操作。它的结构与您在上一次挑战中编写的mapStateToProps()函数类似。它返回一个对象,该对象将调度操作映射到属性名称,后者成为组件props 。但是,每个属性都返回一个函数,该函数使用动作创建者和任何相关的动作数据来调用dispatch ,而不是返回一个state 。您可以访问此dispatch因为它在您定义函数时作为参数传递给mapDispatchToProps() ,就像您将state传递给mapStateToProps() 。在幕后,阵营终极版使用终极版的store.dispatch()进行这些分派mapDispatchToProps()这类似于它将store.subscribe()用于映射到state组件。例如,您有一个loginUser()动作创建者,它将username作为动作有效负载。从mapDispatchToProps()为此动作创建者返回的对象看起来像:
{
submitLoginUser:function(username){
调度(loginUser(用户名));
}
}
## Instructions
代码编辑器提供了一个名为addMessage()的动作创建器。编写函数mapDispatchToProps() ,将dispatch作为参数,然后返回一个对象。该对象应该将一个属性submitNewMessage设置为dispatch函数,该函数在调度addMessage()时为新消息添加一个参数。
## Tests
```yml tests: - text: addMessage应该返回一个带有键typemessage的对象。 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: 使用submitNewMessagemapDispatchToProps调度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.");' ```
## Challenge Seed
```jsx const addMessage = (message) => { return { type: 'ADD', message: message } }; // change code below this line ```
## Solution
```js // solution required ```