3.4 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			3.4 KiB
		
	
	
	
	
	
	
	
id, title, challengeType, isRequired, forumTopicId, localeTitle
| id | title | challengeType | isRequired | forumTopicId | localeTitle | 
|---|---|---|---|---|---|
| 5a24c314108439a4d4036146 | Map Dispatch to Props | 6 | false | 301432 | 映射 Dispatch 到 Props | 
Description
mapDispatchToProps()函数可为 React 组件提供特定的创建 action 的函数,以便组件可 dispatch actions,从而更改 Redux store 中的数据。该函数的结构跟上一挑战中的mapStateToProps()函数相似,它返回一个对象,把 dispatch actions 映射到属性名上,该属性名成为props。然而,每个属性都返回一个用 action creator 及与 action 相关的所有数据调用dispatch的函数,而不是返回state的一部分。你可以访问dispatch,因为在定义函数时,我们以参数形式把它传入mapDispatchToProps()了,这跟state传入mapDispatchToProps()是一样的。在幕后,React Redux 用 Redux 的store.dispatch()来管理这些含mapDispatchToProps()的dispatches,这跟它使用store.subscribe()来订阅映射到state的组件的方式类似。
例如,创建 action 的函数loginUser()把username作为 action payload,mapDispatchToProps()返回给创建 action 的函数的对象如下:
{
  submitLoginUser: function(username) {
    dispatch(loginUser(username));
  }
}
Instructions
addMessage()。写出接收dispatch为参数的函数mapDispatchToProps(),返回一个 dispatch 函数对象,其属性为submitNewMessage。该函数在 dispatch addMessage()时为新消息提供一个参数。
Tests
tests:
  - text: <code>addMessage</code>应返回含<code>type</code>和<code>message</code>两个键的对象。
    testString: assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty('type') && addMessageTest.hasOwnProperty('message')); })());
  - text: <code>mapDispatchToProps</code>应为函数。
    testString: assert(typeof mapDispatchToProps === 'function');
  - text: <code>mapDispatchToProps</code>应返回一个对象。
    testString: assert(typeof mapDispatchToProps() === 'object');
  - text: 从<code>mapDispatchToProps</code>通过<code>submitNewMessage</code>分发<code>addMessage</code>,应向 dispatch 函数返回一条消息。
    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__'); })());
Challenge Seed
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};
// 请在本行以下添加你的代码
Solution
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};
// change code below this line
const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: function(message) {
      dispatch(addMessage(message));
    }
  }
};