Error boundaries与react-router-dom包中的errorElement的比较

huangapple go评论58阅读模式
英文:

Error boundaries vs errorElement from react-router-dom package

问题

我正在学习如何使用 react-router-dom。我刚刚遇到了createBrowserRouter函数中的errorElement属性,我完全理解errorElement属性的工作原理,但我不明白我应该在什么情况下选择错误边界而不是errorElement。它们可以执行相同的任务,但我应该更多地使用哪个,为什么?

英文:

I am learning how to use react-router-dom now. I have just encountered errorElement prop in createBrowserRouter function, I totally understand how errorElement prop works but I can't understand when I should choose error boundaries instead of errorElement. They can perform the same task, but what should I use more and why?

答案1

得分: 4

根据文档,errorElement

> errorElement
>
> 当在加载器操作或组件渲染中抛出异常时,不会按照您的路由的正常渲染路径(<Route element>)进行渲染,而会渲染错误路径(<Route errorElement>),并且错误可以通过useRouteError获得。
>
> 仅当使用数据路由器,如createBrowserRouter 时,此功能才有效。

Route 组件的 errorElement 在处理路由的加载器或操作函数时抛出错误或在渲染路由组件时抛出错误的特定情况下非常有用,您可以渲染更具体和有用的用户界面,而普通的 React 错误边界 适用于意外错误。您可以缩小React错误边界的范围以显示特定的用户界面,但 errorElement 的好处在于更易于使用的API抽象。您不需要自己实现捕获/处理逻辑在自定义错误边界组件中(仅适用于React类组件),而是可以使用useRouteError钩子来访问抛出的错误,并更专注于用户界面。

如果您使用 react-router 数据路由器和路由、路由加载器和操作,那么使用 errorElement 似乎是一个相当明显的选择。

英文:

According to the docs, the errorElement:

> errorElement
>
> When exceptions are thrown in loaders, actions, or component
> rendering, instead of the normal render path for your Routes (&lt;Route
&gt; element&gt;
), the error path will be rendered (&lt;Route errorElement&gt;)
> and the error made available with useRouteError.
>
> This feature only works if using a data router like
> createBrowserRouter

The Route component's errorElement is useful for the specific occasions an error is thrown during processing a route's loader or action functions or when rendering the routed component and you can render more specific and useful UI whereas the regular React error boundaries are more for unexpected errors. You can narrow the scope of a React error boundary to display specific UI, but the benefit of the errorElement is the easier to use API abstraction. You don't need to implement the catch/handling logic yourself in a custom error boundary component (React class component only), but rather you can use the useRouteError hook to access the error that was thrown and you can focus more on the UI.

If you are working with react-router data routers and routes, and route loaders and actions, then using the errorElement seems the rather clear & obvious choice.

huangapple
  • 本文由 发表于 2023年3月4日 01:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定