当 React 路由器参数更改时强制重新安装组件? [英] Force remounting component when React router params changing?

查看:63
本文介绍了当 React 路由器参数更改时强制重新安装组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的应用程序,其中在组件的 componentDidMount 函数中获取远程资源.

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

我正在使用 React Router,当路由完全改变时,之前的组件会很好地卸载,然后新的组件会被安装.

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

问题是当用户停留在同一条路线上时,但仅更改了一些参数.在这种情况下,组件只会更新.这是默认行为.但是有时很难处理所有子组件中的更新,以前只需要 componentDidMount...

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?

谢谢.

推荐答案

执行以下操作

路线应该是这样的.

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

当你去/movie/:movieID

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

这篇关于当 React 路由器参数更改时强制重新安装组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆