React-Router:在导航到其他路径之前将逻辑应用于组件

时间:2018-05-29 19:57:01

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

谢谢。

1 个答案:

答案 0 :(得分:5)

是的,确实如此。 您需要为路由器历史记录对象添加更改侦听器。

为此,请添加具有历史支柱的componentDidMount:

<script>
    $('.box-body').on('change', '.batchCheckboxTransfer', function(){
        alert('hello');
    }
</script>