import React, { Component } from 'react' import type { PropsWithChildren, ErrorInfo, ReactElement } from 'react' import type { AppTrackerConfig } from '../tracker/tracker' import Tracker from '../tracker/tracker' import pubsub from '../utils/pubsub' interface IProps extends AppTrackerConfig { errorViewRender: (cb: () => void) => ReactElement } interface IState { hasError: boolean trackerInstance: Tracker } class ErrorBoundary extends Component, IState> { public static getDerivedStateFromError(error: Error) { // 更新 state 使下一次渲染能够显示降级后的 UI return { hasError: true } } public constructor(props: PropsWithChildren) { super(props) const { accesskey, uploadUrl, pv } = props let trackerInstance = null if (props.accesskey && props.uploadUrl) { trackerInstance = new Tracker({ accesskey, uploadUrl, pv, }) } this.state = { hasError: false, trackerInstance } } public componentDidCatch(error: Error, info: ErrorInfo) { pubsub.publish('ADD', { en: error?.name, em: error?.message, es: error?.stack, createTime: new Date().getTime(), t: 'e', }) } public onPressBack = () => { this.setState({ hasError: false, }) } public render() { if (this.state.hasError) { return this.props.errorViewRender?.(this.onPressBack.bind(this)) || null } return this.props.children } } export default ErrorBoundary