Re-initializing class on redirect

前端 未结 2 429
Happy的楠姐
Happy的楠姐 2020-11-30 15:42

I am currently at http://example.com/parentdir/module/2/

This URL actually loads the Module.js class as indicated in the following route:



        
2条回答
  •  孤城傲影
    2020-11-30 16:15

    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).

提交回复
热议问题