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

允我心安 提交于 2020-05-26 06:05:01

问题


Is it possible to apply logic to a component before navigating to a different route?

For example, my component looks something like this:

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

I'm trying to apply logic such as removing event listeners before the page is navigated to the new route.

I've tried using life cycle methods such as componentWillReceiveProps, componentWillUnmount, and componentShouldUpdate to insert logic before the component is unmounted however they don't seem to be invoked when navigating to a new page.

Does anyone know where or how I can insert logic in between a route change in react-router v4?

Thank you.


回答1:


Yes, it is. You need to add a change listener to you react router history object.

To do this add in your componentDidMount that has the history prop:

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


来源:https://stackoverflow.com/questions/50592020/react-router-apply-logic-to-component-before-navigating-to-a-different-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!