【React】刷新页面或跳转路由时进行二次确认

文章目录

封装hook

js 复制代码
import { useEffect, useRef } from 'react';
import { Prompt, useHistory, useLocation } from 'react-router-dom';

/**
 * 窗口关闭前提醒用户
 *
 * 参考:https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent
 */
export default function useWindowBeforeUnload(getMessage: () => string | undefined) {
  const location = useLocation();
  const history = useHistory();

  const ref = useRef({
    pathname: location.pathname,
  }).current;

  useEffect(() => {
    // 定义提示函数
    const promptBeforeUnload = (event: BeforeUnloadEvent) => {
      const message = getMessage();
      console.log('message before unload', message);

      if (!message) return;

      // 设置提示信息
      event.preventDefault();
      event.returnValue = message;
      return message;
    };

    // 监听 onbeforeunload 事件
    window.addEventListener('beforeunload', promptBeforeUnload);
    return () => window.removeEventListener('beforeunload', promptBeforeUnload);
  });

  //  hash 路由下存在问题,需要谨慎使用
  // 问题:跳转时如果取消了,路由依然会发生辩护,导致下次跳转相同路由,不会出现提示,且刷新页面会进入到目标页面
  const renderPrompt = () => (
    <Prompt
      when={!!getMessage()}
      message={(location, action) => {
        const message = getMessage();
        if (message) return `${message}(即将跳转:${location.pathname}${location.search})`;
        return false;
      }}
    />
  );

  return { renderPrompt };
}

使用hook

js 复制代码
import useWindowBeforeUnload from '@/hooks/useWindowBeforeUnload';

export default function () {
  const { renderPrompt } = useWindowBeforeUnload(() => {
    return '如果有未保存的修改,离开后将会丢失!';
  });

  return (
    <div>
      {renderPrompt()}
    </div>
  );
}
相关推荐
kyle~4 小时前
C++--- override 关键字 强制编译器验证当前函数是否重写基类的虚函数
java·前端·c++
Light605 小时前
像素退场,曲线登场:现代响应式 CSS 全家桶 | 领码课堂
前端·css·响应式设计·css函数·布局系统·相对单位·设计令牌
爱生活的苏苏5 小时前
elementUI 表单验证-联动型校验
前端·javascript·elementui
一只小风华~7 小时前
Vue Router 路由元信息(meta)详解
前端·javascript·vue.js
*且听风吟7 小时前
html 实现鼠标滑动点亮横轴
前端·javascript·html
iCoding919 小时前
前端分页 vs 后端分页:技术选型
前端·后端·系统架构
mingtianyihou339 小时前
使用 Service Worker 限制请求并发数
前端
张可爱9 小时前
20251017-Vue2八股文整理(上篇)
前端
FanetheDivine9 小时前
ts中如何描述一个复杂函数的类型
前端·typescript
lightgis9 小时前
chrome中的axure插件提示无法不受支持
前端·chrome