ComponentDidCatch не работает внутри компонента реакции - PullRequest
0 голосов
/ 04 августа 2020

У меня есть этот компонент. Внутри 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 ]

1 голос
/ 04 августа 2020

Вы должны добавить 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>
0 голосов
/ 04 августа 2020

componentDidCatch

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...