在 React 中按状态状态关闭选项卡时显示消息

Displays message when are Tab closed By State Status in React

当我执行特定过程并且我希望用户不会意外关闭选项卡或重新加载页面时

我需要在他关闭选项卡时提醒他,就像进程继续一样

流程完成后我想取消消息

我该怎么做?

搜索后我找到了执行此操作的代码

const [state, setState] = React.useState(false);
  useEffect(() => {
    const cb = e => {
      if (state) {
        console.log({ s: state });
        e.preventDefault();
        e.returnValue = "Are you sure?";
      }
    };
    window.addEventListener("beforeunload", cb);
    return () => window.removeEventListener("beforeunload", cb);
  }, [state]);

我附上一个例子

codesandbox