react-router 同一路由,參數不同,頁面沒有刷新


使用 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>
    );
  }
}

.


免責聲明!

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



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