【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>
  );
}
相关推荐
qianmoQ14 分钟前
第五章:工程化实践 - 第三节 - Tailwind CSS 大型项目最佳实践
前端·css
C#Thread19 分钟前
C#上位机--流程控制(IF语句)
开发语言·javascript·ecmascript
椰果uu29 分钟前
前端八股万文总结——JS+ES6
前端·javascript·es6
微wx笑1 小时前
chrome扩展程序如何实现国际化
前端·chrome
~废弃回忆 �༄1 小时前
CSS中伪类选择器
前端·javascript·css·css中伪类选择器
CUIYD_19891 小时前
Chrome 浏览器(版本号49之后)‌解决跨域问题
前端·chrome
IT、木易1 小时前
跟着AI学vue第五章
前端·javascript·vue.js
薛定谔的猫-菜鸟程序员1 小时前
Vue 2全屏滚动动画实战:结合fullpage-vue与animate.css打造炫酷H5页面
前端·css·vue.js
春天姐姐2 小时前
vue3项目开发总结
前端·vue.js·git
谢尔登2 小时前
【React】React 性能优化
前端·react.js·性能优化