ErrorBoundary.tsx 1.78 KB
import { Component, type ReactNode } from 'react';

interface Props {
  children: ReactNode;
}
interface State {
  error: Error | null;
}

/**
 * 顶层错误边界:任何渲染期 / 卸载期异常(如地图组件 dispose 抛错)都不该让整页变白。
 * 兜底显示可读信息 + 返回登录按钮,而不是 silent 白屏。
 */
export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: unknown) {
    console.error('[ErrorBoundary] 捕获到未处理的渲染错误:', error, info);
  }

  private backToLogin = () => {
    window.location.href = '/login';
  };

  render() {
    if (this.state.error) {
      return (
        <div
          style={{
            height: '100vh',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 16,
            padding: 24,
            fontFamily: 'system-ui, sans-serif',
            color: '#333',
          }}
        >
          <h1 style={{ margin: 0, fontSize: 20 }}>页面出错了</h1>
          <p style={{ maxWidth: 520, textAlign: 'center', color: '#666', lineHeight: 1.6 }}>
            {this.state.error.message || '未知错误'}
          </p>
          <button
            type="button"
            onClick={this.backToLogin}
            style={{
              padding: '8px 20px',
              border: 'none',
              borderRadius: 6,
              background: '#1677ff',
              color: '#fff',
              cursor: 'pointer',
            }}
          >
            返回登录
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}