欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 【React】刷新页面或跳转路由时进行二次确认

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

2025/4/20 11:19:35 来源:https://blog.csdn.net/qq_45677671/article/details/144968426  浏览:    关键词:【React】刷新页面或跳转路由时进行二次确认

文章目录

    • 封装hook
    • 使用hook

封装hook

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 = () => (<Promptwhen={!!getMessage()}message={(location, action) => {const message = getMessage();if (message) return `${message}(即将跳转:${location.pathname}${location.search}`;return false;}}/>);return { renderPrompt };
}

使用hook

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词