React Router - 如何重用根路由中 errorElement 的布局?

问题描述 投票:0回答:1

我正在使用 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
当显示错误页面时?

reactjs react-router react-router-dom
1个回答
10
投票

当出现错误时,这是一种非此即彼的情况。要么条件良好,并且渲染

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 />
      }
    ]
  }
]);

Edit react-router-how-can-i-reuse-my-layout-for-the-errorelement-in-the-root-route

© www.soinside.com 2019 - 2024. All rights reserved.