文章轉(zhuǎn)自我的語雀:https://www.yuque.com/liuyin-zzwa0/ada6ao/va6p77
項目中使用了動態(tài)菜單,其中含有固定和非固定的菜單,但是我們的后端同事只在登陸時返回含有動態(tài)菜單name的數(shù)組。
如何實現(xiàn)?
菜單生成過程
閱讀源碼我們可以發(fā)現(xiàn),在 layouts/BasicLayout中可以看到 menuData 是從 menu.js 中獲取的
export default connect(({ global, setting, menu: menuModel }) => ({
collapsed: global.collapsed,
layout: setting.layout,
menuData: menuModel.menuData,
breadcrumbNameMap: menuModel.breadcrumbNameMap,
...setting,
}))(props => (
<Media query="(max-width: 599px)">
{isMobile => <BasicLayout {...props} isMobile={isMobile} />}
</Media>
));
找到 menuData 的生成方式

image.png
routes 就是運(yùn)行生成的.umi/router.js 的內(nèi)容,將其輸出我們可以直觀的看見它的具體結(jié)構(gòu)

image.png
修改配置路由
在 router.config.js 中使用 dynamic 去標(biāo)志該目錄(路由)是動態(tài)的
{
path: '/profile',
name: 'profile',
icon: 'profile',
dynamic: true,
routes: [
{
path: '/profile/basic',
name: 'basic',
component: './Profile/BasicProfile',
},
{
path: '/profile/basic/:id',
name: 'basic',
hideInMenu: true,
component: './Profile/BasicProfile',
},
{
path: '/profile/advanced',
name: 'advanced',
authority: ['admin'],
dynamic: true,
component: './Profile/AdvancedProfile',
},
],
},
過濾實際路由
大體思路就是對 routes 進(jìn)行數(shù)據(jù)處理,將登錄獲取到的特定路由(這里用 name 屬性標(biāo)識)在 routes 中過濾出來
effects: {
*getMenuData({ payload }, { put }) {
const { routes, authority } = payload;
const routerMap = filterRouters(routes); // 這邊取出實際的路由表
const menuData = filterMenuData(memoizeOneFormatter(routerMap, authority));
// const breadcrumbNameMap = memoizeOneGetBreadcrumbNameMap(menuData);
const breadcrumbNameMap = memoizeOneGetBreadcrumbNameMap(memoizeOneFormatter(routerMap, authority)); //這是修改后的代碼,因為menuData是已經(jīng)過濾掉存在hideInMenu
yield put({
type: 'save',
payload: { menuData, breadcrumbNameMap, routerMap, routerData: routes }, // 將實際的路由一同放入
});
},
},
const filterRouters = routes => {
if (!routes) return [];
const sectionlist = ['profile.advanced']; // 數(shù)組中就是包含的動態(tài)路由
const sectionList = sectionlist.filter(item => item && isString(item));
const oneLevel = sectionList.filter(item => item.split('.').length >= 1).map(item => item.split('.')[0]);
const levelMore = sectionList.filter(item => item.split('.').length > 1);
routes = filterLevel1(routes, oneLevel);
let list = [];
routes.forEach(route => {
let deep = 0;
list.push(filyer(levelMore, route, deep));
});
return list.filter(item => item);
}
const filterLevel1 = (routes, names) => {
return routes.filter(route => !route.dynamic || (route.dynamic && names.includes(route.name)));
}
const filyer = (sectionList, route, deep) => {
let obj = { ...route };
let sections = sectionList.filter(s => s.indexOf(route.name) === 0);
if (!route.dynamic && (!obj.routes || !obj.routes.length)) return obj;
if (!sections.length && route.dynamic && deep !== 0) {
return null;
}
let oneLevel = sections.filter(item => item.split('.').length >= 2).map(item => item.split('.')[1]);
let levelMore = sections.filter(item => item.split('.').length > 2).map(item => item.split('.').slice(1).join('.'));
obj.routes = filterLevel1(obj.routes, oneLevel);
if (levelMore.length) {
let list = [];
deep++;
obj.routes.forEach(item => {
list.push(filyer(levelMore, item, deep));
});
obj.routes = list.filter(a => a);
}
return obj;
}
此時的 menuData 就是我們想要的實際菜單了
應(yīng)用動態(tài)路由
實現(xiàn)不跳轉(zhuǎn)的頁面 404 、403
舊版本(2.x)回到 layouts/BasicLayout 中,從props中取出 routerMap
const baseRouterConfig = this.getRouterAuthority(pathname, routes); // 完整的項目路由
const routerConfig = this.getRouterAuthority(pathname, routerMap); // 賬號的實際路由
權(quán)限組件 Authorized ,使用這個組件就能實現(xiàn)不跳轉(zhuǎn)的 404、403頁面了
<Content className={styles.content} style={contentStyle}>
{/* 先校驗完整的項目路由 */}
<Authorized authority={baseRouterConfig} noMatch={<Exception404 />}>
{/* 校驗賬號的實際路由 */}
<Authorized authority={routerConfig} noMatch={<Exception403 />}>
{children}
</Authorized>
</Authorized>
</Content>
新版本(3.x)在 layouts/BasicLayout 組件中移除了權(quán)限組件并在 `pages/Authorized.js`使用了登錄狀態(tài)判斷,但這樣同樣會出現(xiàn)[嵌套路由](https://www.yuque.com/liuyin-zzwa0/ada6ao/qi3n6u) umi404的情況,因此我們需要對 `pages/Authorized.js` 進(jìn)行改造。
import React from 'react';
import Redirect from 'umi/redirect';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import Authorized from '@/utils/Authorized';
import { getAuthority } from '@/utils/authority';
import Exception403 from '@/pages/Exception/403';
import Exception404 from '@/pages/Exception/404';
//import { checkpass } from '@/pages/RoutingCheck';
const checkpass = (routeData = [], pathname) => {
let pass = false;
if (!routeData || !routeData.length) return true;
routeData.forEach(route => {
if (pathToRegexp(`${route.path}`).exec(pathname)) {
pass = true;
} else if (!pass && route.routes) {
pass = checkpass(route.routes, pathname)
}
});
return pass;
}
function AuthComponent({ children, location, routerData, routerMap }) {
const { pathname } = location;
const auth = getAuthority();
const isLogin = auth && auth[0] !== 'guest';
const getRouteAuthority = (path, routeData = []) => {
let authorities;
routeData.forEach(route => {
// match prefix
if (pathToRegexp(`${route.path}(.*)`).test(path)) {
authorities = route.authority || authorities;
// get children authority recursively
if (route.routes) {
authorities = getRouteAuthority(path, route.routes) || authorities;
}
}
});
return authorities;
};
const baseAuthority = getRouteAuthority(pathname, routerData)
, baseRouteChecked = checkpass(routerData, pathname)
, actualAuthority = getRouteAuthority(pathname, routerMap)
, actualRouteChecked = checkpass(routerMap, pathname);
return (
<Authorized
authority={baseRouteChecked ? baseAuthority : ['notMacth']}
noMatch={isLogin
? <Exception404 />
: <Redirect to="/user/login" />
}
>
<Authorized
authority={actualRouteChecked ? actualAuthority : ['notMacth']}
noMatch={<Exception403 />}
>
{children}
</Authorized>
</Authorized>
);
}
export default connect(({ menu }) => ({
routerData: menu.routerData,
routerMap: menu.routerMap,
}))(AuthComponent);
但是3.x的寫法會導(dǎo)致出現(xiàn)404或者403時會全屏,所以如果是局部應(yīng)用的話,可以將登錄校驗、404/403校驗分離,將 Routes 分別掛在對應(yīng)的路由層級上