在导航到其他路线之前是否可以将逻辑应用于组件?
例如,我的组件看起来像这样:
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
)
}
}
我试图在页面导航到新路由之前应用逻辑,例如删除事件侦听器。
我尝试使用componentWillReceiveProps
,componentWillUnmount
和componentShouldUpdate
等生命周期方法在卸载组件之前插入逻辑但是它们似乎不是导航到新页面时调用。
有没有人知道我在何处或如何在react-router v4中的路由更改之间插入逻辑?
谢谢。
答案 0 :(得分:5)
是的,确实如此。 您需要为路由器历史记录对象添加更改侦听器。
为此,请添加具有历史支柱的componentDidMount:
<script>
$('.box-body').on('change', '.batchCheckboxTransfer', function(){
alert('hello');
}
</script>