3.7 KiB
3.7 KiB
id, title, challengeType, isRequired, videoUrl, localeTitle
id | title | challengeType | isRequired | videoUrl | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d4036147 | Connect Redux to React | 6 | false | 将Redux连接到React |
Description
mapStateToProps()
和mapDispatchToProps()
函数,您可以使用它们将state
和dispatch
映射到您的某个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