gpt4 book ai didi

javascript - React 中确认警报后 onDelete 不起作用

转载 作者:行者123 更新时间:2023-12-02 20:54:34 26 4
gpt4 key购买 nike

在用户离开 React 页面之前会显示确认警报。如果他们回答"is",我想运行 onDelete()。如果它们也响应“否”,下面的代码将运行 onDelete()

componentDidMount() {
this.setupBeforeUnloadListener();
}

setupBeforeUnloadListener() {
window.addEventListener("beforeunload", (event) => {
event.returnValue = `Are you sure you want to leave?`;
this.onDelete();
})
}

仅当用户在确认警报中回答"is"时,如何才能运行 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() 函数执行任何异步操作,则不能保证完成。有关更多信息,请参阅此讨论:What are the limitation using before unload event?

关于javascript - React 中确认警报后 onDelete 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61520467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com