react-router url参数更新 但是页面不更新的解决办法

今天发现, 当使用react-router(v4.2.2)时,路由需要传入参数, 但是如果路由跳转时,url仅仅改变的是参数部分,如从hello/1跳转到hello/2,此时虽然参数更新了,但是页面是不会更新的,这也算是react-router的一个设计缺陷吧
发现网上的解决方法主要有两种
一、先跳转到一个与当前页面不仅仅是路由参数不同的页面,然后再跳转回来,这样路由跳转了两次。如下所示:
this.props.history.push('/empty'); // 空白页面
setTimeout(() => {
  this.props.history.replace(`/hello/${id}`); // 要跳转的页面,其中id为参数
});

但是这样的话白白加载了一个页面,个人感觉不是很好

二、第二种方法是使用 componentWillReceiveProps(newProps) 函数,当 props 改变时,我们就可以在该函数中通过 newProps.match.params.id 拿到新的url参数,进而进行更新。如下
componentWillReceiveProps(newProps) {
  const id = newProps.match.params.id;
  // 一些操作
}
我个人比较喜欢这种方法
但是如果使用这种方法的话,需要注意的一点是:我们可能在react中使用的的组件不止一个,需要执行 componentWillReceiveProps 方法的组件可能是作为子组件存在的。也就是说react-router直接作用的组件是使用 componentWillReceiveProps 组件的父组件
这个时候路由参数的改变是监测不到的,为了能够监测到,需要在父组件中把 props 传给子组件,就像这样
<Route path="/hello/:id" component={MyHome} />
 
export default class MyHome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
 
  render() {
    return (
      // react-router当url参数改变时不能自动更新页面,为了url参数改变时能够自动更新
      // 在子组件中使用componentWillReceiveProps(),当props改变时会自动调用该函数
      // 但是现在url的参数是直接作用在page(当前页面组件)上的,为了让子组件监测到props
      // 的变化,将props全部传给子组件
       <UserInfo {...this.props} />
    );
  }
}

export default class UserInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
 
  componentWillReceiveProps(newProps) {
    const id = newProps.match.params.id;
    //一些操作
  }
 
  render() {
    return (
      <div className="userinfo-container">
      </div>
    );
  }
}
如有错误,欢迎留言指出

参考:

https://www.cnblogs.com/gdsblog/p/7348375.html

 

https://segmentfault.com/q/1010000010522122

 

http://www.shenyujie.cc/2018/03/04/reactRouter_v1/

 

posted @ 2019-01-24 23:17  一川official  阅读(15231)  评论(0编辑  收藏  举报