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

标签 reactjs react-router react-router-v4 react-router-dom

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

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

  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/

相关文章:

javascript - 将多个对象值显示为表单 Reactjs 中的输入值

typescript - 引用错误 : Request is not defined when testing with React Router v6. 4

javascript - 使用 react 路由器进行模态对话框身份验证

reactjs - typescript :为什么 Material-UI "withStyles()"不能使用显式构造函数?

reactjs - NavLink 或 Link inside the nav of react-router-DOM is updating the URL .But it is not updating the component

javascript - React.js 如何从函数组件访问 Router Link URL 中的参数?

javascript - 如何在不不断重新安装的情况下将包装组件传递到 React Router

reactjs - 用 enzyme 测试链接

reactjs - React router.push 和 router.replace 之间的区别?

javascript - 为什么我在 Reactjs 中 <img> 的高度/宽度没有改变?