// 错误边界
import React from 'react';

interface IProps {
  [key: string]: any;
}
interface IState {
  hasError: boolean;
}

class ErrorBoundary extends React.PureComponent<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = { hasError: false };
  }
  // 此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数，并返回一个值以更新 state
  static getDerivedStateFromError(error: any) {
    console.error(error)
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>{this.props.errorText ?? '组件错误'}</h1>;
    }
    return (
      <>{this.props.children}</>
    )
  }
}

export default ErrorBoundary;
