需要防止更改我的组件中的 url。因此,需要显示一条消息,如果用户选择取消 - 不要更改 URL,如果确定 - 更改 URL。我如何在下一个 13.4 中实现这个逻辑
这是我目前的逻辑,但行不通。我什至没有看到window.confirm消息
useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const mess = window.confirm('Are you sure you want to leave?');
event.returnValue = mess;
if (!mess) {
event.preventDefault();
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
这似乎对我有用,即使我在 StackOverflow 代码片段中尝试也是如此。
window.addEventListener('beforeunload', function (event) {
const unsavedChanges = true;
if (unsavedChanges) {
const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
event.returnValue = confirmationMessage;
return confirmationMessage;
}
});
<button onclick="window.location.reload()">reload</button>