[英]React & MobX - Confirmation dialog when a user navigates away from the existing page
我有这样的东西:
import React from 'react';
import PropTypes from 'prop-types';
import { Prompt } from 'react-router-dom';
const ConfirmationDialog = (props) => {
if (props.navigatingAway) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = null;
}
return (
<Prompt
when={props.navigatingAway}
message="Are you sure?"
/>
);
};
ConfirmationDialog.propTypes = {
navigatingAway: PropTypes.bool.isRequired,
};
export default ConfirmationDialog;
我正在尝试找出扩展此方法的最佳方法,以便navigatingAway
实际上可以执行某些操作。 我不知道要使用什么标准,只是在以下情况下它应该触发确认窗口:
什么when
检查URL更改的最佳方法是when
?
当一种情况发生时,您无需想出一种“检测”方法。
- 用户更改URL并尝试导航
- 用户刷新浏览器
这些已经通过将回调分配给onbeforeunload
。
- 用户点击链接
如果您正在使用react-router
处理导航,则已经通过呈现Prompt
来处理此问题。
props.navigatingAway
的话,会得到更好的命名props.shouldPreventNavigation
或类似的规定,因为其应,如果你要防止浏览,你不是是否进行导航。
例如,如果您始终希望在安装ConfirmationDialog
同时在导航之前出现提示,则props.shouldPreventNavigation
应该始终为true,就可以完成了。 一个常见的用例是,如果表单中有未保存的数据,则将其设置为true。
您可以始终渲染它,而可以通过
when={true}
或when={false}
来阻止或允许进行相应的导航,而不是有条件地在防护罩后面渲染<Prompt>
。
为了说明这一点,除了性能等方面,以下两个片段在功能上是等效的:
render() {
return (
<Prompt
when={this.props.navigatingAway}
message="Are you sure?"
/>
)
}
render() {
if (this.props.navigatingAway) {
return (
<Prompt
when={true}
message="Are you sure?"
/>
)
}
return null;
}
如果在when={true}
Prompt
无法立即正常使用,则可能是您的路由未由react-router
正确管理。
附带说明一下,请确保您考虑了window.onbeforeunload
情况,例如,如果在为ConfirmationDialog
分配了回调时将其卸载,则该操作会发生。 使用适当的生命周期方法进行管理,否则在进行测试时会变得很奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.