How can I make use of Error boundaries in functional React components?

后端 未结 2 683
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 23:07

I can make a class an error boundary in React by implementing componentDidCatch.

Is there a clean approach to making a functional component into an error bo

2条回答
  •  走了就别回头了
    2021-02-04 23:40

    As of v16.2.0, there's no way to turn a functional component into an error boundary.

    The React docs are clear about that, although you're free to reuse them as many times as you wish:

    The componentDidCatch() method works like a JavaScript catch {} block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application.

    Also bear in mind that try/catch blocks won't work on all cases.
    If a component deep in the hierarchy tries to updates and fails, the try/catch block in one of the parents won't work -- because it isn't necessarily updating together with the child.

提交回复
热议问题