1

我正在尝试在反应应用程序中添加实现延迟加载,该应用程序在顶级路由中运行良好。但我也希望<Suspense></Suspense>and 为嵌套路由提供后备。根据 react-router-dom ,必须只有FragmentRoute作为 的子级Routes。有没有办法处理这个?

这是代码:

import { lazy, Fragment, Suspense } from "react";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";

import Header from "./components/Header";

const Home = lazy(() => import("./components/layout/Home"));
const Destination = lazy(() => import("./components/layout/Destination"));
const Planet = lazy(() => import("./components/Planet"));
const Crew = lazy(() => import("./components/layout/Crew"));
const Biography = lazy(() => import("./components/Biography"));
const Technology = lazy(() => import("./components/layout/Technology"));
const Procedure = lazy(() => import("./components/Procedure"));

function App() {
  return (
    <BrowserRouter>
      <Header />
      <Suspense fallback={<p className='fixed left-1/2 top-1/2 -translate-x-1/2 text-2xl'>Loading ...</p>}>
        <Routes>
          <Route path="/" element={<Navigate to="home" />} />
          <Route path="home" element={<Home />} />
          <Route path="destination" element={<Destination />}>
            <Route path=":id/:planet" element={<Planet />} />
          </Route>
          <Route path="crew" element={<Crew />}>
            <Route path=":id" element={<Biography />} />
          </Route>
          <Route path="technology" element={<Technology />}>
            <Route path=":id" element={<Procedure />} />
          </Route>
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

export default App;
4

1 回答 1

1

您可以将单个路由组件包装在它们自己的Suspense.

例子:

<BrowserRouter>
  <Header />
  <Suspense
    fallback={(
      <p className='fixed left-1/2 top-1/2 -translate-x-1/2 text-2xl'>
        Loading ...
      </p>
    )}
  >
    <Routes>
      ...
      <Route path="destination" element={<Destination />}>
        <Route
          path=":id/:planet"
          element={(
            <Suspense fallback={<>Loading Planet ...</>}>
              <Planet />
            </Suspense>
          )}
        />
      </Route>
      ...
    </Routes>
  </Suspense>
</BrowserRouter>
于 2022-02-10T08:04:04.143 回答