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;
|
}
|
}
|