如果你的项目需要很多个路由 传统的路由方式就显得十分臃肿
因此我们需要对路由模块化
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 发送给了子组件