Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/connect-redux-to-react.md

2.2 KiB
Raw Blame History

id, title, challengeType, forumTopicId
id title challengeType forumTopicId
5a24c314108439a4d4036147 连接 Redux 和 React 6 301426

--description--

既然写了mapStateToProps()mapDispatchToProps()两个函数,现在你可以用它们来把statedispatch映射到 React 组件的props了。React Redux 的connect方法可以完成这个任务。此方法有mapStateToProps()mapDispatchToProps()两个可选参数,它们是可选的,原因是你的组件可能仅需要访问状态但不需要分发任何 actions反之亦然。

为了使用此方法,需要传入函数参数并在调用时传入组件。这种语法有些不寻常,如下所示:

connect(mapStateToProps, mapDispatchToProps)(MyComponent)

注意: 如果要省略connect方法中的某个参数,则应当用null替换这个参数。

--instructions--

在编辑器上有两个函数:mapStateToProps()mapDispatchToProps(),还有一个叫Presentational的 React 组件。用ReactRedux全局对象中的connect方法将此组件连接到 Redux并立即在Presentational组件中调用,把结果赋值给一个名为ConnectedComponent的代表已连接组件的新常量。大功告成!你已成功把 React 连接到 Redux尝试更改任何一个connect参数为null并观察测试结果。

--hints--

应渲染Presentational组件。

assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(AppWrapper));
    return mockedComponent.find('Presentational').length === 1;
  })()
);

Presentational组件应通过connect接收一个messages属性。

assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(AppWrapper));
    const props = mockedComponent.find('Presentational').props();
    return props.messages === '__INITIAL__STATE__';
  })()
);

Presentational组件应通过connect接收一个submitNewMessage属性。

assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(AppWrapper));
    const props = mockedComponent.find('Presentational').props();
    return typeof props.submitNewMessage === 'function';
  })()
);

--solutions--