处理 React 的导航事件
我认为您正在寻找的是 getUserConfirmation 组件的 getUserConfirmation 属性。
传递给 prop 的函数可能如下所示(TypeScript 示例):
const getUserConfirmation = (
message: string,
callback: (ok: boolean) => void
): void => {
const answer = window.confirm("Do you want to navigate away?");
// do something depending on which button was pressed
callback(answer); // allow or disallow React's navigation
};
在您定义路线的地方:
<BrowserRouter getUserConfirmation={getUserConfirmation}>
... routes go here ...
</BrowserRouter>
不过,您仍然需要使用 <Prompt>:
<Prompt
when={boolean}
message="This string will be supplied in the confirmation function above as second parameter"
/>
处理浏览器刷新
您可能想要添加这样的回调
window.onbeforeunload = () => {
// some non-blocking logic
return true;
};
不再需要后,可以清理:
window.onbeforeunload = null;
查看this SO question,似乎无法开箱即用地捕获用户对onbeforeunload 中的原生确认窗口的响应。
window.onunload 可能是清理您的资料的正确位置,因为这很可能意味着用户已选择离开该页面。