如何防止React组件中的卸载? [英] How can I prevent the unmount in React Components?
问题描述
我正在尝试在我的应用中实现一项功能,当用户尝试离开未提交的表单时,他们会得到确认,询问他们是否确定要在保存之前离开更改。
I'm trying to implement a feature in my app where when the user tries to navigate away from an un-submitted form, they're given an confirm that asks them if they're sure they want to leave before saving their changes.
componentWillUnmount 方法似乎是完美的候选方法,因为它会触发用户放弃表单的各种方式(更改导致它消失的父组件状态,导航到不同的路径等...)。但是......当确认返回false时,我无法阻止卸载。
The componentWillUnmount method seems like perfect candidate for this because it will fire for all the various ways that a user may abandon the form (changes a parent component state that causes it to disappear, navigates to a different route, etc...). However... I have no way to prevent the unmount when the confirm returns false.
有关如何实现此功能的任何建议吗?
Any suggestions on how I can go about implementing this?
推荐答案
最好通过react-router处理:setRouteLeaveHook。
This is best handled via react-router: setRouteLeaveHook.
componentWillMount() {
this.unregisterLeaveHook = props.router.setRouteLeaveHook(props.route, this.routerWillLeave.bind(this));
}
routerWillLeave(nextLocation) {
return false;
}
卸载组件后,取消注册离开钩子:
And when component is unmounted, unregister the leave hook:
componentWillUnmount() {
this.unregisterLeaveHook();
}
这篇关于如何防止React组件中的卸载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!