22 lines
973 B
TypeScript
22 lines
973 B
TypeScript
import { Component, ReactNode } from 'react';
|
|
|
|
interface State { hasError: boolean; error?: Error }
|
|
export class ErrorBoundary extends Component<{ children: ReactNode }, State> {
|
|
state: State = { hasError: false };
|
|
static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; }
|
|
componentDidCatch(error: Error, info: any) { console.error('UI 错误兜底:', error, info); }
|
|
render() {
|
|
if (this.state.hasError) {
|
|
return (
|
|
<div style={{ padding: 24, color: '#f88', background: '#2a1518', height: '100vh', fontFamily: 'Consolas, monospace', fontSize: 13, whiteSpace: 'pre-wrap' }}>
|
|
<h2>界面发生异常</h2>
|
|
<p>错误:{this.state.error?.message}</p>
|
|
<pre>{this.state.error?.stack}</pre>
|
|
<button onClick={() => location.reload()} style={{ marginTop: 12, padding: '6px 16px', cursor: 'pointer' }}>重试</button>
|
|
</div>
|
|
);
|
|
}
|
|
return this.props.children;
|
|
}
|
|
}
|