我想知道如何手动删除特定路由的setRouteLeaveHook。此页面说在大多数情况下我不需要手动执行此操作,但没有提到如果需要,我该如何执行此操作。
在大多数情况下,您无需手动拆除路线离开钩子。离开关联路由后,我们会自动删除所有附加的路由离开钩子。
原因可能最好通过示例来解释。
class Editor extends Component {
componentDidMount(){
const { dispatch, dirty, route } = this.props;
const { router } = this.context;
router.setRouteLeaveHook(route, this.routerWillLeave.bind(this));
}
routerWillLeave(nextLocation){
console.debug('routerWillLeaveCalled -> ', this.props);
let { dirty, dispatch, resetForm } = this.props;
const { router } = this.context;
if (dirty) {
let dialog = {
id: Date.now(),
showTitle: true,
titleContent: 'Unsaved Changes',
titleIcon: 'fa fa-warning',
content: <span>You have <strong>unsaved</strong> changes! <strong>Discard</strong> them?</span>,
type: 'confirm',
handleCloseClick: (e) => {
e.preventDefault();
dispatch(closeDialog());
},
acceptBtn: {
title: 'Okay',
handler: (e) => {
e.preventDefault();
resetForm();
console.debug('handler dirty ->', dirty);
dispatch(push(nextLocation));
// dispatch(closeDialog());
}
},
denyBtn: {
title: 'Deny',
handler: (e) => {
e.preventDefault();
dispatch(closeDialog());
}
}
}
dispatch(addDialogWindow(dialog));
dispatch(openDialog(false, (e) => dispatch(closeDialog()), false));
return false;
}
return true;
}
}
我遇到的问题是acceptBtn
.调用 redux-forms resetForm()
函数后,编辑器组件尚未更新(使用新 props,我不确定为什么),这意味着在调用 dirty 时仍设置为 true dispatch(push(nextLocation));
。
流程如下所示:
- 单击链接会导致不同的路由。
- 路由器WillLeave是第一次被调用。它调度一些显示我的对话框的操作(有两个按钮接受和拒绝)。
- 当第一次点击acceptBtn时,发生的事情是再次调用routeWillLeave(因为它仍然挂着)。出于某种原因,此时即使已调度
resetForm()
组件仍未更新,这意味着dirty == true
并且再次执行相同的代码块。 - 第二次单击acceptBtn现在将再次触发routerWillLeave,但这次
dirty == false
,因此它返回true并且路由会按预期更改。
以下是首次单击acceptBtn
后调度的操作。
action @ 01:26:08.101 redux-form/RESET
action @ 01:26:08.105 @@router/CALL_HISTORY_METHOD
action @ 01:26:08.117 ADD_DIALOG_WINDOW
action @ 01:26:08.127 OPEN_DIALOG
这是在第二次单击它之后。
action @ 01:26:02.235 ADD_DIALOG_WINDOW
action @ 01:26:02.239 OPEN_DIALOG
action @ 01:26:08.101 redux-form/RESET
action @ 01:26:08.105 @@router/CALL_HISTORY_METHOD
action @ 01:26:08.117 ADD_DIALOG_WINDOW
action @ 01:26:08.127 OPEN_DIALOG
action @ 01:43:10.358 redux-form/RESET
action @ 01:43:10.363 @@router/CALL_HISTORY_METHOD
action @ 01:43:10.372 @@router/LOCATION_CHANGE
action @ 01:43:10.670 redux-form/DESTROY
action @ 01:43:10.676 redux-form/DESTROY
因此,我想做的是删除acceptBtn的处理程序函数中的钩子。这可能/可以吗?还是我做错了什么,或者有更好的方法来实现这一目标?
删除 setRouteLeaveHook 钩子。
let remove = router.setRouteLeaveHook(route, (nextLocation) => {
remove()
})
似乎是调度调用的定时执行问题。将位置调度包装为超时 0 解决了此问题。
acceptBtn: {
title: 'Okay',
handler: (e) => {
e.preventDefault();
resetForm();
// Wait for call stack to unwind and then execute
// the following which will now have the updated values.
setTimeout(() => {
dispatch(push(nextLocation));
dispatch(closeDialog());
}, 0);
}
},