N级路由嵌套的封装
1、 在index.js中BrowserRouter中完成一级路由构建。
<BrowserRouter>
<Route children={(props, params)=>{
const {location, history} = props;
return (
<Switch location={location}>
{Routes.map((router, index)=>{
return this.createChildrenRoute(router, index);
})}
</Switch>)
}}/>
</BrowserRouter>
2、创建函数完成含有子级路由的路由构建。
//定义函数完成路由的构建,该路由包含当前路由对应的自己路由
createChildrenRoute(router, index){
//获取router对象中的路由信息
const {path, component:Father, children} = router;
if(children){
//需要返回一个含有子级路由的路由实例
return <Route key={index} path={path} children={()=>{
return (<Father>
<Switch>
{children.map((child, index1)=>{
return this.createChildrenRoute({...child,path:path+"/"+child.path}, `${index}-${index1}`);
})}
<Redirect from={path} to={path+"/"+children[0].path}></Redirect>
</Switch>
</Father>);
}}/>;
}else{
//返回一个普通的路由实例创建函数完成普通路由的构建。
return this.createBasicRoute(router, index);
}
}
3、创建函数完成普通路由的构建。
// 定义函数完成普通路由的构建
createBaseRoute(route, index) {
return <Route exact path={route.path} component={route.component} key={index}></Route>
}