react中有一级路由二级路由那么该怎么写路由循环
时间: 2024-03-16 08:37:46 浏览: 100
为了在React中实现一级和二级路由,我们可以使用React Router。下面是一个示例,演示如何使用React Router实现一级和二级路由的路由循环:
```javascript
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// 一级路由组件
import Home from './Home';
import About from './About';
import Contact from './Contact';
// 二级路由组件
import Profile from './Profile';
import Settings from './Settings';
// 一级路由数组
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact },
];
// 二级路由数组
const profileRoutes = [
{ path: '/profile', exact: true, component: Profile },
{ path: '/profile/settings', component: Settings },
];
// 路由循环
const RouteWithSubRoutes = (route) => (
<Route
path={route.path}
exact={route.exact}
render={(props) => (
<route.component {...props} routes={route.routes} />
)}
/>
);
// App组件
const App = () => (
<Router>
<Switch>
{routes.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))}
<Route path="/profile" render={() => (
<CompileRouter routes={profileRoutes} />
)} />
</Switch>
</Router>
);
export default App;
```
在上面的代码中,我们首先定义了一级路由和二级路由的组件。然后,我们将一级路由和二级路由分别存储在`routes`和`profileRoutes`数组中。接下来,我们定义了一个`RouteWithSubRoutes`组件,用于循环渲染路由。最后,在`App`组件中,我们使用`Switch`组件来渲染一级路由,并在二级路由的父级路由中使用`CompileRouter`组件来渲染二级路由。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)