当路由发生变化时,如何在react路由器外处理

How to do things when route changes outside react-router?

本文关键字:react 路由器 处理 路由 变化      更新时间:2023-09-26

我在react router之外有一个组件,我想在路由更改时做点什么。如何做到这一点?

class MyComponent extends React.Component {
  constructor(props, context) {
    super(props, context);
    // get location and history here, but I don't know if these can help
    this.context = context;
  }
  //TODO: do something when route changes
  render() {
    return (
      <div>
        my component
      </div>
    );
  }
};
MyComponent.contextTypes = {
  location: React.PropTypes.object,
  history: React.PropTypes.object
};
module.exports = MyComponent;

react路由器的确认导航
也许这就是你所需要的,react route的LifeCycle mixin给出了一个方法"routerWillLeave",当路由改变时会调用该方法