【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>
  );
}
相关推荐
FlowGram5 分钟前
FlowGram 官网建设
前端
晚枫~10 分钟前
零基础快速上手Playwright自动化测试
javascript·python·测试工具·c#·自动化
~无忧花开~11 分钟前
JavaScript学习笔记(二十八):JavaScript性能优化全攻略
开发语言·前端·javascript·笔记·学习·性能优化·js
BumBle12 分钟前
基于UniApp实现DeepSeek AI对话:流式数据传输与实时交互技术解析
前端·uni-app
九十一14 分钟前
vue3事件总线与emit
前端·vue.js
岁月向前1 小时前
不同的协议和场景防丢包方案
前端
琢磨先生TT1 小时前
一个前端工程师的年度作品:从零开发媲美商业级应用的后台管理系统!
前端·前端框架
云枫晖1 小时前
JS核心知识-Ajax
前端·javascript
玄魂1 小时前
VTable Gantt 智能 zoom(缩放)功能介绍与开发实践
前端·开源·数据可视化
Joyee6911 小时前
RN 的初版架构——UI 布局与绘制
前端·react native