useRoutes怎么配置路由
时间: 2023-06-01 14:02:37 浏览: 50
useRoutes是React Router v6中的一个新特性,它用于在函数式组件中使用路由。使用useRoutes需要先安装React Router v6。
以下是使用useRoutes配置路由的步骤:
1. 导入必要的模块
```javascript
import { useRoutes, RouteObject } from 'react-router-dom';
```
2. 定义路由配置
```javascript
const routes: RouteObject[] = [
{
path: '/',
element: <Home />,
children: [
{ path: 'about', element: <About /> },
{ path: 'contact', element: <Contact /> },
],
},
{ path: '*', element: <NotFound /> },
];
```
在这个例子中,我们定义了三个路由:/,/about和/contact,以及一个通配符路由*,当用户访问未定义的路由时,会显示NotFound组件。
3. 使用useRoutes
```javascript
function App() {
const routing = useRoutes(routes);
return <div>{routing}</div>;
}
```
在函数式组件中使用useRoutes,传入定义好的路由配置即可。这样就实现了路由功能。
完整代码示例:
```javascript
import React from 'react';
import { useRoutes, RouteObject } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import NotFound from './NotFound';
const routes: RouteObject[] = [
{
path: '/',
element: <Home />,
children: [
{ path: 'about', element: <About /> },
{ path: 'contact', element: <Contact /> },
],
},
{ path: '*', element: <NotFound /> },
];
function App() {
const routing = useRoutes(routes);
return <div>{routing}</div>;
}
export default App;
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)