簡體   English   中英

無法在反應中觸發 beforeunload 事件

[英]can't trigger beforeunload event in 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 路由器的 Prompt 組件,如下所示:

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

有關此組件的更多信息,請參閱react-router 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM