AppErrorBoundary.tsx
1.28 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
// REQ-USR-003: 路由级 ErrorBoundary(子路由渲染抛错兜底 + 返回主页入口,spec § 3 error / D7)。
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { Button, Result } from 'antd';
interface AppErrorBoundaryProps {
children: ReactNode;
}
interface AppErrorBoundaryState {
hasError: boolean;
}
export default class AppErrorBoundary extends Component<
AppErrorBoundaryProps,
AppErrorBoundaryState
> {
state: AppErrorBoundaryState = { hasError: false };
static getDerivedStateFromError(): AppErrorBoundaryState {
return { hasError: true };
}
componentDidCatch(_error: Error, _info: ErrorInfo): void {
// 兜底:捕获即进入降级 UI;此处可接入日志上报(MVP 不上报)。
}
private handleGoHome = () => {
this.setState({ hasError: false });
// 直接回主页(不依赖 hooks,class 组件用 location)
window.location.assign('/');
};
render() {
if (this.state.hasError) {
return (
<Result
status="error"
title="页面出错,请刷新或返回主页"
extra={
<Button type="primary" onClick={this.handleGoHome}>
返回主页
</Button>
}
/>
);
}
return this.props.children;
}
}