import React, { Component, type ReactNode } from 'react' import Taro from '@tarojs/taro' import { View, Text, Button } from '@tarojs/components' import './ErrorBoundary.scss' interface ErrorBoundaryState { hasError: boolean error?: Error errorInfo?: React.ErrorInfo } interface ErrorBoundaryProps { children: ReactNode fallback?: ReactNode onError?: (error: Error, errorInfo: React.ErrorInfo) => void } class ErrorBoundary extends Component { constructor(props: ErrorBoundaryProps) { super(props) this.state = { hasError: false } } static getDerivedStateFromError(error: Error): ErrorBoundaryState { return { hasError: true, error } } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { this.setState({ error, errorInfo }) this.props.onError?.(error, errorInfo) console.error('ErrorBoundary caught an error:', error, errorInfo) } private handleReset = () => { this.setState({ hasError: false, error: undefined, errorInfo: undefined }) } private handleReload = () => { Taro.reLaunch({ url: '/pages/index/index' }) } render() { if (this.state.hasError) { if (this.props.fallback) return this.props.fallback return ( ! 页面出现了问题 请稍后重试,或返回首页继续使用。 {process.env.NODE_ENV === 'development' && ( 错误详情 {this.state.error?.message} )} ) } return this.props.children } } export default ErrorBoundary