2

I've written a simple app where the remote resources are fetched inside componentDidMount functions of the components.

I'm using React Router and when the route changes completely, the previous component is unmounted well then the new one is mounted.

The issue is when the user is staying on the same route, but only some params are changed. In that case, the component is only updated. This is the default behaviour. But it's sometimes difficult to handle the update in all the children components where previously only componentDidMount was needed...

Is there a way to force the remounting of the component when the user is staying on the same route but some params are changing?

Thanks.

Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
  • Possible duplicate of [How to force remounting on React components?](https://stackoverflow.com/questions/35792275/how-to-force-remounting-on-react-components) – The Reason Dec 28 '17 at 15:15
  • I know it's not the answer you are looking for, but i usually just check if the params changed in componentWillReceiveProps and call the same initialization code that runs in componentDidMount. i.e. `if (this.props.match.userId !== nextProps.match.userId) { initComponent(nextProps.match.userId);}` – brub Dec 28 '17 at 15:28
  • can you tell what version of react-router do you have? – Ilya Lopukhin Dec 28 '17 at 16:25
  • Possible duplicate of [Component does not remount when route parameters change](https://stackoverflow.com/questions/32261441/component-does-not-remount-when-route-parameters-change) – Juha Syrjälä Jan 06 '19 at 09:50

1 Answers1

3

Do the following

the route shoul look like this.

<Route  path='/movie/:movieId'  component={Movie} /> 

When you go to /movie/:movieID

class Movie extends Component {

 loadAllData = (movieID) => {
    //if you load data 
    this.props.getMovieInfo(movieID);
    this.props.getMovie_YOUTUBE(movieID);
    this.props.getMovie_SIMILAR(movieID);
  }
  componentDidMount() {
    this.loadAllData(this.props.match.params.movieId);
  }
  componentWillReceiveProps(nextProps){
    if(nextProps.match.params.movieId !== this.props.match.params.movieId) {
      console.log(nextProps);
      this.loadAllData(nextProps.match.params.movieId);
    }
  }

  render(){
    return( ... stuff  and <Link to={`/movie/${id}`} key={index}>...</Link>)
  }
 }