0

我有这个组件。在里面componentDidMount我创建了一个对象并尝试抛出错误。但是 mycomponentDidCatch没有被调用反而破坏了我的页面!

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>)
  }
}
4

2 回答 2

1

static getDerivedStateFromError如果您想在捕获错误后呈现一些 UI,您应该添加。

此外,错误边界不会捕获错误边界本身引发的错误(这就是我添加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>

于 2020-08-04T06:00:13.157 回答
0

组件DidCatch

在后代组件抛出错误后调用此生命周期。

componentDidCatch不会捕获同一组件引发的错误。

于 2020-08-04T05:49:04.407 回答