React Redux - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

Container component structure

  1. Constructor
    1. Initialize state
    2. Bind functions
  2. Functions implementation
  3. Render (markup, can move to child component)
  4. PropTypes validation
  5. Connect to Redux

Map State to Props

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
    };
}

Map Dispatch to Props

Map actions to Props of compoment for calling in handler.

There are 3 ways:

  • Calling dispatch directly from props
  • Use mapDispatchToProps manually mapping dispatch
  • Mapping dispatch with bindActionCreators

Calling dispatch directly

  • 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,
  // ...
}

Use mapDispatchToProps manually mapping dispatch

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,
  // ...
}

Mapping dispatch with bindActionCreators

  • Import bindActionCreators from redux
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,
  // ...
}

Entry Point

// 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>
⚠️ **GitHub.com Fallback** ⚠️