Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...