react路由嵌套

在config.js 中添加配置项

import Two from "../pages/Home/Two"
import Recommend from "../pages/Recommend/Recemmend";  //导入组件

let routers = [
    {
        path: "/home",   //路由地址
        component: Home,    //路由模板   
        routes: [    //路由嵌套  配置路由嵌套不能使用精准匹配
            {
                path: "/home/recommend",
                component: Recommend,
                exact: true,   //精准匹配
            },
            {
                path: "/home/ranking",
                component: System,
                exact: true,
            },
            {
                path: "/home/two",
                component: Two,
                exact: true,
            },
        ]
    },
    {
        path: "/about",
        component: About,
        exact: true
    },
    {
        path: "/",
        redirect: "/home",   //重定向
    }
]

export default routers;

将配置文件导入到路由组件 index.js


import React, { Component } from 'react';
import { Switch, Route, Redirect } from "react-router-dom";  
import routers from "./config";  //配置文件

class Router extends Component {
    render() {
        return (
            <Switch>
                {routers.map((value, index) => {  //映射注入Route组件中
                    if (!value.redirect) {   //需要重定型执行写下面代码
                        return (
                            <Route key={index} exact={value.exact} path={value.path} component={props => <value.component {...props} routes={value.routes} />} ></Route>
                            //如果有路由嵌套,则将路由签到传递到组件的props中,在传递的组件中再次进行路由配置
                        
                        )
                    } else {
                        return (
                            <Redirect key={index} from={value.path} to={value.redirect}></Redirect>
                            //重定向
                        )
                    }
                })}
            </Switch>
        );
    }
}

export default Router; 将文件导注入到app.js中

app.js

import './App.css';
import React, { Component } from 'react';
import RouterView from './router/index';
class App extends Component {
  render() {
    return (
      <div>
      //将组件使用在app.js中
        <RouterView></RouterView>
      </div>
    );
  }
}

export default App;

在路由嵌套的Home页面中再次配置路由组件;


 render() {
console.log(this.props.routes)   //路由嵌套的配置规则
        return (
            <div className="Home-box">
                <Switch>
                //再次添加路由组件实现路由嵌套
                    {this.props.routes.map((value, index) => <Route key={index} path={value.path} exact={value.exact} component={value.component}></Route>)}
                </Switch>
            </div>
        );
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值