'use client'; import React from 'react'; import { AlertTriangle, RefreshCw } from 'lucide-react'; import { motion } from 'framer-motion'; interface ErrorBoundaryState { hasError: boolean; error: Error | null; } interface ErrorBoundaryProps { children: React.ReactNode; fallback?: React.ComponentType<{ error: Error; resetError: () => void }>; } export class ErrorBoundary extends React.Component { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null }; } static getDerivedStateFromError(error: Error): ErrorBoundaryState { return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error('Error caught by boundary:', error, errorInfo); } resetError = () => { this.setState({ hasError: false, error: null }); }; render() { if (this.state.hasError) { if (this.props.fallback) { const FallbackComponent = this.props.fallback; return ; } return (

出现错误

{this.state.error?.message || '组件渲染时发生错误,请尝试刷新页面或重置组件'}

重试
); } return this.props.children; } } // Hook 版本的错误边界 export function useErrorBoundary() { const [error, setError] = React.useState(null); const resetError = React.useCallback(() => { setError(null); }, []); const captureError = React.useCallback((error: Error) => { setError(error); }, []); React.useEffect(() => { if (error) { throw error; } }, [error]); return { captureError, resetError }; }