You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+React Router如何仅在特定页面阻止用户刷新?

解决特定React路由页面仅触发beforeunload监听的问题

你需要利用React组件的生命周期(或Hooks),在目标表单页面组件挂载时添加监听,卸载时移除监听,就能确保只有该页面生效。

函数组件方案(React Hooks)

在你的表单组件中使用useEffect钩子,添加监听的同时返回清理函数,组件卸载时自动执行清理:

import { useEffect } from 'react';

function FormPage() {
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      // 标准写法:设置returnValue,部分浏览器需要调用preventDefault
      e.preventDefault();
      e.returnValue = "数据将会丢失,确定要离开吗?";
      // 兼容旧浏览器可返回字符串,主流浏览器以returnValue为准
      return "数据将会丢失,确定要离开吗?";
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    // 组件卸载时移除监听
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []); // 空依赖数组确保只在挂载、卸载时执行

  return (
    <div>
      <h1>表单页面</h1>
      <form>
        {/* 表单元素 */}
      </form>
    </div>
  );
}

export default FormPage;

类组件方案

如果使用类组件,在componentDidMount中添加监听,componentWillUnmount中移除:

import React from 'react';

class FormPage extends React.Component {
  componentDidMount() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }

  handleBeforeUnload = (e) => {
    e.preventDefault();
    e.returnValue = "数据将会丢失,确定要离开吗?";
    return "数据将会丢失,确定要离开吗?";
  };

  render() {
    return (
      <div>
        <h1>表单页面</h1>
        <form>
          {/* 表单元素 */}
        </form>
      </div>
    );
  }
}

export default FormPage;

关键说明

  • 当通过React Router切换路由时,表单组件会被卸载,此时清理函数(或componentWillUnmount)会自动移除监听,不会影响其他页面。
  • 不同浏览器对beforeunload的自定义文案支持不同,多数浏览器会显示默认提示,但必须设置returnValue或返回字符串才能触发提示弹窗。

内容的提问来源于stack exchange,提问作者Cyberguy Game

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:36:20