卢春龙
2026-08-17 f525b6c3cc105bd1a997d893937689bebcc9570d
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
import { Component, ReactNode } from 'react';
 
// 通用错误边界:捕获子树在「渲染 / 生命周期」阶段抛出的错误,出错后静默渲染为空,
// 避免动效等非核心 UI 的异常向上冒泡拖垮整个页面。
// 注意:错误边界无法捕获异步回调(requestAnimationFrame、Promise、事件处理器)中的错误,
// 那部分需在对应异步逻辑内自行 try/catch 兜底。
type Props = {
  children: ReactNode;
  /** 出错时的兜底 UI,默认不显示任何内容 */
  fallback?: ReactNode;
};
 
type State = {
  hasError: boolean;
};
 
export default class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false };
 
  static getDerivedStateFromError(): State {
    return { hasError: true };
  }
 
  componentDidCatch(error: any) {
    // eslint-disable-next-line no-console
    console.warn('[Fireworks] 已忽略渲染错误:', error);
  }
 
  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? null;
    }
    return this.props.children;
  }
}