ComponentDidCatch не работает внутри компонента реакции

У меня есть этот компонент. ВнутриcomponentDidMountЯ создал объект и пытаюсь выбросить ошибку. Но мойcomponentDidCatch не был вызван вместо этого разрывает мою страницу!

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      errorInfo: null
    };
  }

  componentDidCatch(error, errorInfo) {
    // Catch errors in any child components and re-renders with an error message
    this.setState({
      error,
      errorInfo
    });
    console.log({ error, errorInfo });
  }

  componentDidMount() {
    const d = {}
    console.log(d.d.d)
  }

  render() {
    console.log("458454545454")
    if (this.state.error) {
      console.log("Error occurred")
    }
    return(<div>dffdfdfdfdfd</div>)
  }
}

2 ответа

Вы должны добавить static getDerivedStateFromError если вы хотите отобразить пользовательский интерфейс после обнаружения ошибки.

Кроме того, границы ошибок не улавливают ошибки, возникающие в самой границе ошибки (поэтому я добавляюFaultyComponent выдает фактическую ошибку).

function FaultyComponent() {
  throw new Error("Test error");

  return <span>Faulty</span>;
}

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }
  
  static getDerivedStateFromError(error) {    
    return { hasError: true };  
  }
  
  componentDidCatch(error, errorInfo) {
    console.log('componentDidCatch', { error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    
    return this.props.children;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <FaultyComponent />
    </ErrorBoundary>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

componentDidCatch

Этот жизненный цикл вызывается после того, как дочерний компонент выдал ошибку.

componentDidCatch не обнаруживает ошибки, вызванные одним и тем же компонентом.

Другие вопросы по тегам