如何在功能性React组件中使用错误边界? [英] How can I make use of Error boundaries in functional React components?

查看:223
本文介绍了如何在功能性React组件中使用错误边界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使类成为错误边界在React中通过实现 componentDidCatch

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 boundary without converting it into a class?

还是这是代码的味道?

推荐答案

从v16.2.0开始,无法将功能组件转换为错误边界。

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

React文档对此很清楚,尽管您可以随意重复使用它们多次:

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


componentDidCatch()方法的工作原理类似于JavaScript catch {} 块,但用于组件。 仅类组件可以是错误边界。实际上,大多数情况下,您只需要声明一次错误边界组件并在整个应用程序中使用它。

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.

还请记住, try / catch 阻止不适用于所有情况

如果组件很深在层次结构中尝试更新并失败时,其中一个父级中的 try / catch 块将不起作用-因为它不一定与子级一起更新。

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.

这篇关于如何在功能性React组件中使用错误边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆