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
dispatchdirectly fromprops - Use
mapDispatchToPropsmanually mapping dispatch - Mapping dispatch with
bindActionCreators
-
connectfunction
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))
}
}-
connectfunction
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
bindActionCreatorsfromredux
import {bindActionCreators} from 'redux';mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
}
}-
connectfunction
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);- Trigger the dispatch
onClickSave(){
this.props.actions.createCourse(this.state.course);
}- Add validation,
actionsis 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>