[英]Using React error boundary with react router
我們正在嘗試將 react-error-boundary 與 react-router (v6) 一起使用,但似乎我們需要用錯誤邊界包裝每個路由元素,如下所示
import { ErrorBoundary } from "react-error-boundary";
export const AppRoutes = createBrowserRouter([
{
path: "/",
element: <ErrorBoundary FallbackComponent={GlobalError}><Login /></ErrorBoundary>
},
{
path: "login",
element: <ErrorBoundary FallbackComponent={GlobalError}><Login /></ErrorBoundary>,
},
{
path: "trans",
element: <ErrorBoundary FallbackComponent={GlobalError}><Trans /></ErrorBoundary>
),
{
path: "*",
element: <ErrorBoundary FallbackComponent={GlobalError}><RouteNotFound /></ErrorBoundary>
}]);
我們有像下面這樣更簡單的方法嗎? react-router 中的任何配置標志冒出錯誤
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary FallbackComponent={GlobalError}>
<Header />
<RouterProvider router={AppRoutes} />
<Footer />
</ErrorBoundary>
下面是我們將 RouterProvider 包裝在錯誤邊界內時得到的錯誤的屏幕截圖
下面是 Trans 組件拋出錯誤的示例代碼。
export function Trans() {
const [error, setError] = useState(null);
if (error) {
throw error;
}
useEffect(() => {
setTimeout(() => setError("This is error"), 2000);
}, []);
return <p>This is Trans</p>;
}
代碼片段應該可以工作,但是如果你想讓代碼更干,那么你可以創建一個布局路由來渲染一個由ErrorBoundary
組件包裹的Outlet
組件,而不是單獨包裝每個路由。
例子:
import { createBrowserRouter, Outlet } from 'react-router-dom';
import { ErrorBoundary } from "react-error-boundary";
const ErrorBoundaryLayout = () => (
<ErrorBoundary FallbackComponent={GlobalError}>
<Outlet />
</ErrorBoundary>
);
export const AppRoutes = createBrowserRouter([
{
element: <ErrorBoundaryLayout />,
children: [
{
path: "/",
element: <Login />,
},
{
path: "login",
element: <Login />,
},
{
path: "trans",
element: <Trans />,
},
{
path: "*",
element: <RouteNotFound />,
},
],
},
]);
對於 React 錯誤邊界,您應該注意這一點:
筆記
錯誤邊界不會捕獲以下錯誤:
- 事件處理程序(了解更多)
- 異步代碼(例如 setTimeout 或 requestAnimationFrame 回調)
- 服務器端渲染
- 錯誤邊界本身(而不是其子項)中拋出的錯誤
在您的Trans
組件示例中,您使用setTimeout
來設置一些錯誤 state。我只能猜測這里的思考過程可能是某些錯誤被認為是“不可恢復的”,因此錯誤邊界會啟動並處理它,否則錯誤發生在以上幾點被認為是“可恢復的”,您的組件代碼應該被編碼為可能處理異步問題的場景,如失敗的獲取請求等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.