我正在使用 React Router v6,以下是我的路线:
const router = createBrowserRouter([
{
path: '/',
element: <App />,
errorElement: <ErrorPage />,
children: [
{
index: true,
element: <HomePage />,
},
{
path: '/sign-up',
element: <SignUpPage />,
},
{
path: '/log-in',
element: <LogInPage />,
},
],
},
]);
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement,
);
root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
App
组件包含我的应用程序的布局,并使用Outlet
组件输出路线元素。但是现在,如果出现错误冒泡到根路径,那么 ErrorPage
会按预期显示,但它不会使用 App
中的布局...那么,我如何重用我的布局App
当显示错误页面时?
当出现错误时,这是一种非此即彼的情况。要么条件良好,并且渲染
App
组件,要么或者 出现错误条件,并且渲染 ErrorPage
组件。
您可以做的是将
App
组件的布局部分抽象为自己的布局组件,该组件可以渲染传递的 children
prop 或 嵌套路由的 Outlet
组件,然后渲染将其放入 App
中,并包裹 ErrorPage
组件。
示例:
const AppLayout = ({ children }) => (
...
{children ?? <Outlet />}
...
);
const App = () => (
...
<AppLayout />
...
);
const router = createBrowserRouter([
{
path: "/",
element: <App />, // <-- uses Outlet
errorElement: (
<AppLayout> // <-- uses children
<ErrorPage />
</AppLayout>
),
children: [
{
index: true,
element: <HomePage />
},
{
path: "/sign-up",
element: <SignUpPage />
},
{
path: "/log-in",
element: <LogInPage />
}
]
}
]);