import React, { Component } from 'react';
import isEqual from 'lodash/isEqual';

interface IProps {
  id: number;
  data: any;
}

interface IState {
  hasError: boolean;
}

export default class ComErrorBoundary extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error: Error) {
    console.error(`组件发生错误（id:${this.props.id}）:`, error);
  }

  componentDidUpdate(prevProps) {
    const { data: prevData } = prevProps;

    if (!isEqual(prevData, this.props.data) && this.state.hasError) {
      this.setState({
        hasError: false
      });
    }
  }

  render() {
    if (this.state.hasError) {
      return null;
    }

    return this.props.children;
  }
}
