React Redux - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
- Constructor
- Initialize state
- Bind functions
- Functions implementation
- Render (markup, can move to child component)
- PropTypes validation
- Connect to Redux
Mapping Redux State to Props of component whenever the Redux State changes.
// state: Redux state
// ownProps: component's props
function mapStateToProps(state, ownProps) {
return {
appState: state
};
}
- Note: When mapStateToProps is CPU intensively, memoize (https://github.com/addyosmani/memoize.js) for performance (caching returned value when input does not change).
Map actions to Props of compoment for calling in handler.
There are 3 ways:
- Calling
dispatch
directly fromprops
- Use
mapDispatchToProps
manually mapping dispatch - Mapping dispatch with
bindActionCreators
-
connect
function
export default connect(mapStateToProps)(CoursesPage);
- Trigger the dispatch
onClickSave(){
this.props.dispatch(courseActions.createCourse(this.state.course));
}
- Add validation
CoursesPage.propTypes = {
dispatch: PropTypes.func.isRequired,
// ...
}
This is a preferred way in 3 options. The main reason is that all the actions are defined explicitly in props
mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
createCourse: course => dispatch(courseActions.createCourse(course))
}
}
-
connect
function
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
- Trigger the dispatch
onClickSave(){
this.props.createCourse(this.state.course);
}
- Add validation
CoursesPage.propTypes = {
createCourse: PropTypes.func.isRequired,
// ...
}
- Import
bindActionCreators
fromredux
import {bindActionCreators} from 'redux';
mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
}
}
-
connect
function
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
- Trigger the dispatch
onClickSave(){
this.props.actions.createCourse(this.state.course);
}
- Add validation,
actions
is object
CoursesPage.propTypes = {
actions: PropTypes.object.isRequired,
// ...
}
// Create Redux store and configure it with reducers
const store = configureStore();
// Provider component sends store to its children through props
ReactDOM.render(
<Provider store={store}>
<app />
</Provider>