Error handling in React best practices

后端 未结 4 658
别跟我提以往
别跟我提以往 2020-12-13 13:15

When rendering a component in React (with many subcomponents) and a JS error is thrown for whatever reason, what\'s the best way to handle this? Sure I can catch the error

4条回答
  •  不思量自难忘°
    2020-12-13 13:45

    A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”.

    Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

    A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info)

    ref link

提交回复
热议问题