freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/map-dispatch-to-props.chine...

3.6 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036146 Map Dispatch to Props 6 false 将调度映射到道具

Description

mapDispatchToProps()函数用于为React组件提供特定的操作创建器以便它们可以针对Redux存储分派操作。它的结构与您在上一次挑战中编写的mapStateToProps()函数类似。它返回一个对象,该对象将调度操作映射到属性名称,后者成为组件props 。但是,每个属性都返回一个函数,该函数使用动作创建者和任何相关的动作数据来调用dispatch ,而不是返回一个state 。您可以访问此dispatch因为它在您定义函数时作为参数传递给mapDispatchToProps() ,就像您将state传递给mapStateToProps() 。在幕后,阵营终极版使用终极版的store.dispatch()进行这些分派mapDispatchToProps()这类似于它将store.subscribe()用于映射到state组件。例如,您有一个loginUser()动作创建者,它将username作为动作有效负载。从mapDispatchToProps()为此动作创建者返回的对象看起来像:
{
submitLoginUserfunctionusername{
调度loginUser用户名;
}
}

Instructions

代码编辑器提供了一个名为addMessage()的动作创建器。编写函数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")); })(), "<code>addMessage</code> should return an object with keys <code>type</code> and <code>message</code>.");'
  - text: <code>mapDispatchToProps</code>应该是一个函数。
    testString: 'assert(typeof mapDispatchToProps === "function", "<code>mapDispatchToProps</code> should be a function.");'
  - text: <code>mapDispatchToProps</code>应该返回一个对象。
    testString: 'assert(typeof mapDispatchToProps() === "object", "<code>mapDispatchToProps</code> should return an object.");'
  - text: 使用<code>submitNewMessage</code>的<code>mapDispatchToProps</code>调度<code>addMessage</code>应该向调度函数返回一条消息。
    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 <code>addMessage</code> with <code>submitNewMessage</code> from <code>mapDispatchToProps</code> should return a message to the dispatch function.");'

Challenge Seed

const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

// change code below this line

Solution

// solution required