gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:58:38 26 4
gpt4 key购买 nike

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

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

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

谢谢。

最佳答案

是的,确实如此。您需要向 react 路由器历史对象添加一个更改监听器。

要执行此操作,请在具有历史属性的 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'});
}

关于reactjs - React-Router:在导航到不同的路由之前将逻辑应用于组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com