项目中,经常会出现几个页面共用一个组件的情况,而且几个页面的流程是一致的,为了方便页面的管理和后期的维护性,我们需要使用页面嵌套页面的这种形式去开发。
这里用react-router-dom来实现:
首先引入需要用到的组件
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
然后定义好我们的嵌套路由:
const routerConfig = [{
path: "/father",
component: Father,
children: [
{
path: "/child1",
component: Child1,
redirect: true
},
{
path: "/child2",
component: Child2,
}
],
},
// ....
]
现在我们写路由:
const RouterComp = props => {
return (
<Suspense fallback={<div></div>}>
<Router children={createRoute(routerConfig)} />
</Suspense>
);
}
const createRoute = routes => {
return (
<Switch>
{
routes.map((route, index) =>
createFixRoute(route, index)
)
}
<Redirect from='/*' to='/' />
</Switch>
);
};
//该组件通过递归的方式,将所有route中带有children路由的父路由进行解构,最终用createBasicRoute函数来渲染
const createFixRoute = (route, index) => {
const { path, component: RouteComponent, children } = route;
if (children) {
return (
<Route
key={index}
path={path}
children={props => {
let redirectPath = null;
return <RouteComponent {...props}>
<Switch>
{children.map((child, index2) => {
const { path: childPath, redirect } = child;
if (redirect){
redirectPath = childPath;
}
return createFixRoute({...child, path: path + childPath}, `${index}-${index2}`);
})}
<Redirect from={`${path}`} to={`${path}${redirectPath || children[0].path}`} />
</Switch>
</RouteComponent>;
}}
/>
);
} else {
return createBasicRoute(route, index);
}
};
const createBasicRoute = (route, index) => { // 最基础的Router 用法
const { path, component: Component } = route;
return <Route exact key={index} path={path} component={props => {
props.history.listen(path => { // 路由监听
...
});
return <Component {...props} />;
}} />;
};
撒花!!
嵌套路由的写法在当我们有多个页面需要复用组件的时候,优势很大:
1.方便传值,不需要在每个页面重新给复用的组件赋值
2.减少了dom节点的更新,变相地提高了页面的流畅性
3.从路由上就能很清晰地看到每个流程包含的页面
4.优雅!