import { Component, type ReactNode } from 'react'; interface Props { children: ReactNode; fallback?: ReactNode; } interface State { hasError: boolean; error: Error | null; } export class ErrorBoundary extends Component { constructor(props: Props) { super(props); this.state = { hasError: false, error: null }; } static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; } componentDidCatch(error: Error, info: React.ErrorInfo) { console.error('[ErrorBoundary]', error, info.componentStack); } render() { if (this.state.hasError) { if (this.props.fallback) return this.props.fallback; return (

界面发生异常

{this.state.error?.message ?? '渲染过程中出现未知错误,请尝试刷新页面。'}

); } return this.props.children; } }