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

3.7 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036147 Connect Redux to React 6 false 将Redux连接到React

Description

现在您已经编写了mapStateToProps()mapDispatchToProps()函数,您可以使用它们将statedispatch映射到您的某个React组件的props 。 React Redux的connect方法可以处理此任务。此方法采用两个可选参数: mapStateToProps()mapDispatchToProps() 。它们是可选的,因为您可能拥有只需要访问state但不需要分派任何操作的组件,反之亦然。要使用此方法,请将函数作为参数传递,并立即使用组件调用结果。这种语法有点不寻常,看起来像: connect(mapStateToProps, mapDispatchToProps)(MyComponent) 注意:如果要省略connect方法的其中一个参数,则在其位置传递null

Instructions

代码编辑器具有mapStateToProps()mapDispatchToProps()函数以及一个名为Presentational的新React组件。使用ReactRedux全局对象中的connect方法将此组件连接到Redux并立即在Presentational组件上调用它。将结果分配给名为ConnectedComponent的新const ,该const表示连接的组件。就是这样现在你已经连接到Redux了尝试将connect的参数更改为null并观察测试结果。

Tests

tests:
  - text: <code>Presentational</code>组件应该呈现。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("Presentational").length === 1; })(), "The <code>Presentational</code> component should render.");'
  - text: <code>Presentational</code>组件应通过<code>connect</code>接收prop <code>messages</code> 。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return props.messages === "__INITIAL__STATE__"; })(), "The <code>Presentational</code> component should receive a prop <code>messages</code> via <code>connect</code>.");'
  - text: <code>Presentational</code>组件应通过<code>connect</code>接收prop <code>submitNewMessage</code> 。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return typeof props.submitNewMessage === "function"; })(), "The <code>Presentational</code> component should receive a prop <code>submitNewMessage</code> via <code>connect</code>.");'

Challenge Seed

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

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

After Test

console.info('after the test');

Solution

// solution required