英文:
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 (<Route
), the error path will be rendered (
> element><Route errorElement>
)
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论