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

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

我想将延迟加载应用于特定路线。我想要这样的东西:

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;

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

javascript reactjs react-router lazy-loading react-suspense
2个回答
1
投票

只有

Route
React.Fragment
组件是
Routes
组件的有效子组件。
Suspense
需要在其他地方渲染。

您可以将各个路由包装在

Suspense
组件中:

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

0
投票

lazy
属性用于
Route
组件:

https://reactrouter.com/en/main/route/lazy

const routes = createRoutesFromElements(
  <Route path="/" element={<Layout/>}>
    <Route path="a" lazy={() => import("./LazyOne")} />
    <Route path="b" element={<NotLazy/>} />
  </Route>
)
© www.soinside.com 2019 - 2024. All rights reserved.