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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…