无法在 react 中触发卸载前事件



我想在用户单击后退按钮时触发beforeunload事件。我已经为beforeunload事件设置了事件侦听器,如下所示

useEffect(() => {
const cb = (ev) => {
ev.preventDefault();
return (ev.returnValue =
"Changes might not be saved. Are you sure you want to close?");
};
window.addEventListener("beforeunload", cb);
return () => window.removeEventListener("beforeunload", cb);
}, []);

下面是检测返回按钮何时被点击的代码:

const history = useHistory();
useEffect(() => {
return () => {
if (history.action === "POP") {
//ACTION TO BE DONE
console.log("hoho", history.action);
window.dispatchEvent(new Event("beforeunload"));
}
};
});

当我点击后退按钮时,我可以看到'hoho POP',但事件没有被触发。我该如何解决这个问题?

我的目的是显示关于丢失未保存的更改的弹出框,当beforeunload事件被触发时显示。虽然我仍然无法触发beforeunload事件,但我设法找出了各种各样的解决方案。

我没有触发这个事件,而是简单地使用了react router的Prompt组件,如下所示:

<Prompt message="Leaving this page will cause you to lose unsaved data. Are you sure?" />

有关该组件的更多信息,请参阅react-router文档

最新更新