import React, { Component, ErrorInfo, ReactNode } from 'react'; import { hydrationDebug } from '../utils/hydrationDebug'; interface Props { children: ReactNode; fallback?: ReactNode; } interface State { hasError: boolean; error?: Error; } class ErrorBoundary extends Component { public state: State = { hasError: false, }; public static getDerivedStateFromError(error: Error): State { // 更新 state 使下一次渲染能够显示降级后的 UI return { hasError: true, error }; } public componentDidCatch(error: Error, errorInfo: ErrorInfo) { console.error('ErrorBoundary caught an error:', error, errorInfo); // 使用调试工具记录水合错误 if (error.message.includes('hydration') || error.message.includes('Hydration')) { hydrationDebug.logHydrationError(error, 'ErrorBoundary'); } } public render() { if (this.state.hasError) { // 自定义降级 UI if (this.props.fallback) { return this.props.fallback; } return (

页面加载出错

抱歉,页面加载时出现了问题。这可能是由于网络连接或浏览器兼容性问题导致的。

{this.state.error?.message.includes('hydration') && (

检测到水合错误。请尝试刷新页面或清除浏览器缓存。

)}
{process.env.NODE_ENV === 'development' && this.state.error && (
查看错误详情
                  {this.state.error.message}
                  {this.state.error.stack}
                
)}
); } return this.props.children; } } export default ErrorBoundary;