react笔记 路由嵌套

如果你的项目需要很多个路由  传统的路由方式就显得十分臃肿

因此我们需要对路由模块化

import xxxrouter   记住  不要在import上面定义变量  会报错

let routes = [{
    path: "/",
    component: Home,
    exact: true
}, {
    path: "/News",
    component: News,
    exact: false
}, {
    path: "/",
    component: Home,
    exact: true
}, {
    path: "/",
    component: Home,
    exact: true
},]

class XXX

是不是对写法很熟悉?  没错  与vue中的路由模块化写法相同

我们需要在render 中循环遍历这个routes数组   route 可以自己起名  最常用的是val 因为写路由

改为了route

      {
        routes.map((route,key)=>{
          if(route.exact){
            return <Route key={key} exact path={route.path} component={route.component}></Route>
          }else{
            return <Route key={key} path={route.path} component={route.component}></Route>
          }
        
        })
      }

这样就做到了路由的模块化

我们可以选择将routes封装为一个model 引入组件 随后将 export暴露出来 在需要的页面引入这个model

2 子路由的嵌套

import xxxrouter   记住  不要在import上面定义变量  会报错

let routes = [{
    path: "/",
    component: Home,
    exact: true
}, {
    path: "/News",
    component: News,
    exact: false,
    routes:[{  //注意 这里不能用children 和react本身的属性名发生冲突
        path: "/News/xxx",
        component: newsXxx,
    },{
        path: "/News/xxx",
        component: newsXxx,
    },]
}, {
    path: "/",
    component: Home,
    exact: true
}, {
    path: "/",
    component: Home,
    exact: true
},]

class XXX

为了不搞混  使用和vue相同的写法

你的子组件需要得到父组件的路由来判断自己是谁的子组件

在app这类父组件路由触发时传递当前的路由  传给子组件

在router中无法通过props传递参数  因此我们需要换一种方式

 <Route path="/news" component={News} ></Route>

render={props=>(
    <route.component {...props} routes={route.routes)/>
)}
这样就成功把当前路由的子组件路由 routes 发送给了子组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值