React中react-router-dom最新版本如何实现延迟加载

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

我想使用 Typescript 在 React 中实现延迟加载。我收到打字稿错误。

const App = () => {
  return (
    <RouterProvider
      router={createBrowserRouter(
        createRoutesFromElements(
          <Route>           
            <Route path="/" element={<Outlet/>}>
              <Route index element={<Home />} />               
              <Route path="contact" element={<Contact />} />
              <Route path="about" element={<About />} />
              <Route path="*" element={<Navigate to="/" replace />} />
            </Route>           
          </Route>
        )
      )}
    />
  )
};

export default App;

下面的代码不起作用

<Route>           
  <Route path="/" element={<Outlet/>}>
    <Route index lazy={() => import("./Home")} />               
    <Route path="contact" lazy={() => import("./Contact")} />
    <Route path="about" lazy={() => import("./About")} />
    <Route path="*" element={<Navigate to="/" replace />} />
  </Route>           
</Route>
reactjs typescript react-router-dom
1个回答
0
投票
const Home= lazy(() => import("./screens/home"));
const About= lazy(() => import("./screens/about"));
<Route>           
  <Route path="/" element={<Outlet/>}>
   <Route index    element={<Suspense fallback={<div>Loading...</div>}>
                      <Home/>
                    </Suspense> /> } />
    <Route path="about" element={<Suspense fallback={<div>Loading...</div>}>
                      <About/>
                    </Suspense> /> }  />         
  
    <Route path="*" element={<Navigate to="/" replace />} />
  </Route>           
</Route>
© www.soinside.com 2019 - 2024. All rights reserved.