Skip to content

componentWillReceiveProps and mapDispatchToProps #221

@iammerrick

Description

@iammerrick

I am running into an issue where componentWillReceiveProps is being called to early, namely before React Redux has had the opportunity to bind a different function based on the props passed. The previous function is still bound when componentWillReceiveProps is called. Take for example this component:

const App = ReactRedux.connect((state, props) => ({
  name: props.userId ? state.user.name : state.group.groupName
}), (dispatch, props) => {
  return Redux.bindActionCreators({
    load: props.userId ? loadUser : loadGroup
  }, dispatch);
})(class extends React.Component {
  componentWillMount() {
    this.props.load();
  }
  componentWillReceiveProps() {
    this.props.load();
  }
  render() {
    return <div>Hello {this.props.name}!</div>;
  }
});

We want to bind a different function to load (based on the userId prop) and a different data to props based on the property provided. Unfortunately when componentWillReceiveProps is called, the old function is still bound to load. This can be "hacked" by introducing a setTimeout in your componentWillReceiveProps that makes sure the next component is actually bound.

I've made a full example of this on jsbin: http://jsbin.com/faqama/edit?html,js,output

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions