Connecting React To Redux
Use the React-Redux library
Provider | Connect |
---|---|
Attaches app to store | function that generates container components |
1. You must wrap your top level component with the Provider component
<Provider store={this.props.store}>
<App />
</Provider>
2. Use the connect function to connect to the Redux store by wrapping your component
export default connect(
mapStateToProps,
mapDispatchToProps
)(MyContainerComponent)
3. Pass connect 2 functions, specify state and actions to expose to the component
function mapStateToProps(state, ownProps) {
return { appState: state.authorReducer };
}
export default connect(mapStateToProps, mapDispatchToProps)(MyContainerComponent)
4. Expose a specific part of state from the Redux store via mapStateToProps
const mapStateToProps = (state, ownProps) => {
return ({
location: state.location,
account: (!isEmptyObject(state.login) && !isEmptyObject(state.login.account)) ?
state.login.account : {},
});
};
5. Using mapDispatchToProps to dispatch actions - wrap action creators in dispatch call for you. Child components do not have to know anything about Redux.
function mapDispatchToProps(dispatch) {
return (
loadCourses: () => {
dispatch(loadCourses());
},
createCourse: () => {
dispatch(createCourse(course));
},
updateCourse: () => {
dispatch(updateCourse(course));
}
);
}