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
.");'
```