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

.

猜你喜欢

转载自www.cnblogs.com/crazycode2/p/12180560.html
今日推荐