reactjs 如何使用React Router选择性地将延迟加载和暂停应用到特定路由?

avkwfej4  于 2023-05-22  发布在  React
关注(0)|答案(1)|浏览(138)

我想对特定路由应用延迟加载。我想要这样的东西:

import { lazy, Suspense } from "react";
import { Route, Routes } from "react-router-dom";
import NotLazyComponent from "./NotLazyComponent";

const LazyOne = lazy(() => import("./LazyOne"));
const LazyTwo = lazy(() => import("./LazyTwo"));

const App = () => {
  return (
    <Routes>
      <Route path="/not-lazy" element={<NotLazyComponent />} />
      <Suspense fallback={<div>Loading...</div>}>
        <Route path="/lazy-one" element={<LazyOne />} />
        <Route path="/lazy-two" element={<LazyTwo />} />
      </Suspense>
    </Routes>
  );
};

export default App;

但这行不通正确的方法是什么?

5kgi1eie

5kgi1eie1#

只有RouteReact.Fragment组件是Routes组件的有效子组件。Suspense需要在其他地方渲染。
您可以在Suspense组件中 Package 单个路由:

const App = () => {
  return (
    <Routes>
      <Route path="/not-lazy" element={<NotLazyComponent />} />
      <Route
        path="/lazy-one"
        element={(
          <Suspense fallback={<div>Loading...</div>}>
            <LazyOne />
          </Suspense>
        )}
      />
      <Route
        path="/lazy-two"
        element={(
          <Suspense fallback={<div>Loading...</div>}>
            <LazyTwo />
          </Suspense>
        )}
      />
    </Routes>
  );
};

创建包含延迟加载的嵌套管线组件的布局管线:

import { Routes, Route, Outlet } from 'react-router-dom';

const SuspenseLayout = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <Outlet />
  </Suspense>
);

const App = () => {
  return (
    <Routes>
      <Route path="/not-lazy" element={<NotLazyComponent />} />
      <Route element={<SuspenseLayout />}>
        <Route path="/lazy-one" element={<LazyOne />} />
        <Route path="/lazy-two" element={<LazyTwo />} />
      </Route>
    </Routes>
  );
};

或者在ReactTree中将Suspense组件提升到Routes组件之外:

const App = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/not-lazy" element={<NotLazyComponent />} />
        <Route path="/lazy-one" element={<LazyOne />} />
        <Route path="/lazy-two" element={<LazyTwo />} />
      </Routes>
    </Suspense>
  );
};

相关问题