React 中确认警报后 onDelete 不起作用
在 React 中,确认警报在用户离开页面之前显示。如果他们回答“是”,我想运行
onDelete()
。如果他们也回答“否”,以下代码将运行
onDelete()
。
componentDidMount() {
this.setupBeforeUnloadListener();
}
setupBeforeUnloadListener() {
window.addEventListener("beforeunload", (event) => {
event.returnValue = `Are you sure you want to leave?`;
this.onDelete();
})
}
如何仅当用户在确认警报中回答“是”时才运行
onDelete()
。
您可以尝试将
unload
事件与
beforeunload
一起使用。
beforeunload
将为用户提供取消卸载的机会,如果用户不取消卸载,则会触发
unload
事件。
请注意,大多数浏览器都会忽略任何自定义提示字符串 https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:
Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292). Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).
此外,如果您的 onDelete() 函数执行任何异步操作,则不能保证完成。有关更多信息,请参阅此讨论: 使用卸载前事件有哪些限制?