【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>
  );
}
相关推荐
biubiuibiu7 分钟前
JavaScript核心概念深度解析:位运算与短路逻辑
开发语言·javascript·ecmascript
fengfuyao98510 分钟前
一个改进的MATLAB CVA(Change Vector Analysis)变化检测程序
前端·算法·matlab
yuhaiqiang43 分钟前
为什么这道初中数学题击溃了所有 AI
前端·后端·面试
djk88881 小时前
支持手机屏幕的layui后台html模板
前端·html·layui
紫_龙1 小时前
最新版vue3+TypeScript开发入门到实战教程之watch详解
前端·javascript·typescript
okra-1 小时前
Axure RP 10 进阶指南:从全局变量到JavaScript语法,打造高效原型设计!
javascript·axure·photoshop
默默学前端1 小时前
ES6模板语法与字符串处理详解
前端·ecmascript·es6
lxh01131 小时前
记忆函数 II 题解
前端·javascript
我不吃饼干2 小时前
TypeScript 类型体操练习笔记(三)
前端·typescript
华仔啊2 小时前
除了防抖和节流,还有哪些 JS 性能优化手段?
前端·javascript·vue.js