ErrorBoundary.tsx
1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Component, type ReactNode } from 'react';
interface Props {
children: ReactNode;
}
interface State {
error: Error | null;
}
/**
* 顶层错误边界:任何渲染期 / 卸载期异常(如地图组件 dispose 抛错)都不该让整页变白。
* 兜底显示可读信息 + 返回登录按钮,而不是 silent 白屏。
*/
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: unknown) {
console.error('[ErrorBoundary] 捕获到未处理的渲染错误:', error, info);
}
private backToLogin = () => {
window.location.href = '/login';
};
render() {
if (this.state.error) {
return (
<div
style={{
height: '100vh',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 16,
padding: 24,
fontFamily: 'system-ui, sans-serif',
color: '#333',
}}
>
<h1 style={{ margin: 0, fontSize: 20 }}>页面出错了</h1>
<p style={{ maxWidth: 520, textAlign: 'center', color: '#666', lineHeight: 1.6 }}>
{this.state.error.message || '未知错误'}
</p>
<button
type="button"
onClick={this.backToLogin}
style={{
padding: '8px 20px',
border: 'none',
borderRadius: 6,
background: '#1677ff',
color: '#fff',
cursor: 'pointer',
}}
>
返回登录
</button>
</div>
);
}
return this.props.children;
}
}