怎么实现根据路由名称 动态加载页面
时间: 2024-04-13 21:30:18 浏览: 13
要根据路由名称动态加载页面,你可以使用React Router的动态导入功能(Dynamic Import)。这样可以根据路由名称来异步加载对应的页面组件。
首先,在路由配置文件(比如`AppRouter.tsx`)中,你可以使用React Router的`lazy`函数和`Suspense`组件来实现动态导入:
```tsx
import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
const AppRouter: React.FC = () => {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</Router>
);
};
export default AppRouter;
```
在上述示例中,我们使用`lazy`函数和动态导入来异步加载`Home`和`About`组件。然后,我们使用`Suspense`组件来提供一个加载中的界面(在本例中是一个简单的文本提示)。
接下来,在你的根组件中使用这个路由器,就像之前一样:
```tsx
import React from 'react';
import AppRouter from './AppRouter';
const App: React.FC = () => {
return (
<div>
<h1>My React App</h1>
<AppRouter />
</div>
);
};
export default App;
```
现在,当你访问对应的路由时,React将会根据需要异步加载对应的页面组件。
这样,根据路由名称动态加载页面就实现了。请注意,在使用动态导入时,确保你的路由配置和组件路径正确无误。
希望对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)