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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM