React-Router:在导航到不同的路由之前将逻辑应用于组件

React-Router: Apply logic to component before navigating to a different route

是否可以在导航到不同的路线之前将逻辑应用于组件?

例如,我的组件看起来像这样:

  class Example extends React.Component {

    //Handles logic for when user leaves page
    handlePageExit = () => {
        console.log("Leaving page...");
    }

    //Set onBeforeUnload event listener so handlePageExit function is called when user closes or refreshes page
    componentDidMount = () => {
        window.addEventListener("onbeforeunload", this.handlePageExit);
    }

    //This hook is called when page exits or is refreshed 
    //It will remove event listener when 
    //However, it wont be called when user changes to a new route
    componentWillMount = () => {
        window.removeEventListener("onbeforeunload", this.handlePageExit)
    }

    //There's no react life cycle hook I can use to call HandlePageLogic when user navigates to a new route to remove event listener or apply other logic...

    render(){
        return(
          <div /> //Not relevant to question
        )
    }
}

我正在尝试应用逻辑,例如在页面导航到新路由之前删除事件侦听器。

我试过使用componentWillReceivePropscomponentWillUnmountcomponentShouldUpdate等生命周期方法在组件卸载之前插入逻辑,但它们似乎没有被调用导航到新页面时。

有谁知道我可以在哪里或如何在 react-router v4 中的路由更改之间插入逻辑?

谢谢。

是的,是的。 您需要添加一个更改侦听器来响应路由器历史记录对象。

为此,请添加具有 history 属性的 componentDidMount:

componentDidMount() {
    this.props.history.listen(this.onRouteChange.bind(this));
  }

onRouteChange(route) {
//route.pathname = Your next route

//Handle what you need to do here
//if you need to redirect you can do this
     this.props.history.replace({pathname: '/desiredRoute'});
  }