React-Router:在导航到不同的路由之前将逻辑应用到组件 [英] React-Router: Apply logic to component before navigating to a different route

查看:38
本文介绍了React-Router:在导航到不同的路由之前将逻辑应用到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我已经尝试使用生命周期方法,例如 componentWillReceivePropscomponentWillUnmountcomponentShouldUpdate 在卸载组件之前插入逻辑,但是它们导航到新页面时似乎没有被调用.

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.

有谁知道我可以在 react-router v4 中的路由更改之间插入逻辑的位置或方式吗?

Does anyone know where or how I can insert logic in between a route change in react-router v4?

谢谢.

推荐答案

是的.您需要为您的反应路由器历史记录对象添加一个更改侦听器.

Yes, it is. You need to add a change listener to you react router history object.

为此添加具有历史属性的 componentDidMount:

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

这篇关于React-Router:在导航到不同的路由之前将逻辑应用到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆