React TS 路由懒加载:单路由出口组件代码示例
下面是一个使用 React、TypeScript 和 React Router 的示例代码,展示如何在只有一个路由出口的 App 中实现路由懒加载:
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
const NotFound = lazy(() => import('./components/NotFound'));
const App: React.FC = () => {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route component={NotFound} />
</Switch>
</Suspense>
</Router>
);
};
export default App;
在这个代码示例中,我们使用 lazy
函数来实现路由组件的懒加载。import('./components/Home')
中的路径是相对于当前文件的路径,你需要根据你的项目结构进行调整。
Suspense
组件用于在加载路由组件时显示一个加载中的状态。你可以在 fallback
属性中传入一个加载中的元素,例如 <div>Loading...</div>
。
Switch
组件用于确保只有一个路由组件被渲染。在这个例子中,我们先匹配 exact path='/' component={Home}
路由,然后是 path='/about' component={About}
路由,最后是 component={NotFound}
路由,它将会匹配任何其他路径。
注意,上述代码中使用的 BrowserRouter
组件是 React Router 的一种路由模式。你也可以根据需要使用其他的路由模式,例如 HashRouter
或 MemoryRouter
。
希望这个代码片段能够帮助你!

原文地址: http://www.cveoy.top/t/topic/qA9G 著作权归作者所有。请勿转载和采集!