反应路由器:在导航到其他路由之前将逻辑应用于组件



是否可以在导航到其他路由之前将逻辑应用于组件?

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

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 的路由更改之间插入逻辑?

谢谢。

是的。 您需要将更改侦听器添加到您的反应路由器历史记录对象。

为此,请添加具有历史记录属性的组件DidMount:

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

最新更新