Force remounting component when React router params changing?

泄露秘密 提交于 2020-12-12 11:10:35

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/48009825/force-remounting-component-when-react-router-params-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!