Re-initializing class on redirect

The id is passed as a prop in the form of this.props.params.id so you should use the componentWillReceiveProps lifecycle method which runs everytime the props change which is what is happening in your case.

The componentWillMount method will not run when you navigate from /parentdir/module/2 to /parentdir/module/3 as the component is already mounted. It will only run when you navigate from some other component (when you go directly for example).

In your Module component add this lifecycle method

componentWillReceiveProps(nextProps){
      if(nextProps.params.id != this.props.params.id){
          //load information etc (whatever you are doing in componentWillMount)
       }
}

What is happening is that when it receives the newer set of props it’s comparing if the param id has changed (all route params live in the params object in props) and when it sees there is a change it carries out the logic. The comparison is not really necessary and you can add the logic as is in the componentWillReceiveProps method but that would be inefficient as it is called everytime the props object changes (might not be the id param at all).

Leave a Comment