mapStateToProps()和mapDispatchToProps()函数,您可以使用它们将state和dispatch映射到您的某个React组件的props 。 React Redux的connect方法可以处理此任务。此方法采用两个可选参数: mapStateToProps()和mapDispatchToProps() 。它们是可选的,因为您可能拥有只需要访问state但不需要分派任何操作的组件,反之亦然。要使用此方法,请将函数作为参数传递,并立即使用组件调用结果。这种语法有点不寻常,看起来像: connect(mapStateToProps, mapDispatchToProps)(MyComponent) 注意:如果要省略connect方法的其中一个参数,则在其位置传递null 。 mapStateToProps()和mapDispatchToProps()函数以及一个名为Presentational的新React组件。使用ReactRedux全局对象中的connect方法将此组件连接到Redux,并立即在Presentational组件上调用它。将结果分配给名为ConnectedComponent的新const ,该const表示连接的组件。就是这样,现在你已经连接到Redux了!尝试将connect的参数更改为null并观察测试结果。 Presentational组件应该呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("Presentational").length === 1; })(), "The Presentational component should render.");'
- text: Presentational组件应通过connect接收prop messages 。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return props.messages === "__INITIAL__STATE__"; })(), "The Presentational component should receive a prop messages via connect.");'
- text: Presentational组件应通过connect接收prop submitNewMessage 。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return typeof props.submitNewMessage === "function"; })(), "The Presentational component should receive a prop submitNewMessage via connect.");'
```