react 面包屑
// 路由展示如下
1 const Routers = [ 2 { 3 name: '业务受理', 4 breadcrumb: '业务受理', 5 path: '/', 6 redirect: '/identification', 7 component: Identification, 8 exact: true, 9 }, 10 { 11 name: '身份证明申请', 12 breadcrumb: '身份证明申请', 13 path: '/identification', 14 component: Identification, 15 exact: true, 16 }, 17 { 18 name: '身份证明申请详情', 19 path: '/identification/:id', 20 component: IdentificationDetail, 21 exact: true, 22 }, 23 { 24 name: '营业资质证明申请', 25 breadcrumb: '营业资质证明申请', 26 path: '/qualification', 27 component: Identification, 28 exact: true, 29 }, 30 { 31 name: '营业资质证明申请详情', 32 path: '/qualification/:name', 33 component: QualificationDetail, 34 exact: true, 35 }, 36 { 37 name: '专业投资者认定', 38 breadcrumb: '专业投资者认定', 39 path: '/investor', 40 component: Identification, 41 exact: true, 42 }, 43 { 44 name: '专业投资者认定详情', 45 path: '/investor/:name', 46 component: InvestorDetail, 47 exact: true, 48 }, 49 { 50 name: '身份证明申请', 51 breadcrumb: '身份证明申请', 52 path: '/*', 53 redirect: '/identification', 54 exact: true, 55 }, 56 57 ]
1 const getBreadcrumbs = ({ flattenRoutes, location }) => { 2 // 初始化匹配数组match 3 let matches = []; 4 5 location.pathname 6 // 取得路径名,然后将路径分割成每一路由部分. 7 .split('?')[0] 8 .split('/') 9 // 对每一部分执行一次调用`getBreadcrumb()`的reduce. 10 .reduce((prev, curSection) => { 11 // 将最后一个路由部分与当前部分合并,比如当路径为 `/x/xx/xxx` 时,pathSection分别检查 `/x` `/x/xx` `/x/xx/xxx` 的匹配,并分别生成面包屑 12 const pathSection = `${prev}/${curSection}`; 13 const breadcrumb = getBreadcrumb({ 14 flattenRoutes, 15 curSection, 16 pathSection, 17 }); 18 19 // 将面包屑导入到matches数组中 20 matches.push(breadcrumb); 21 22 // 传递给下一次reduce的路径部分 23 return pathSection; 24 }); 25 return matches; 26 }; 27 const getBreadcrumb = ({ flattenRoutes, curSection, pathSection }) => { 28 const matchRoute = flattenRoutes.find(ele => { 29 const { path } = ele; 30 // exact 为 react router4 的属性,用于精确匹配路由 31 return matchPath(pathSection, { path, exact: true }); 32 }); 33 // 返回breadcrumb的值,没有就返回原匹配子路径名 34 if (matchRoute) { 35 return { 36 content: matchRoute.breadcrumb || decodeURI(curSection), 37 path: matchRoute.path, 38 }; 39 } 40 // 对于routes表中不存在的路径 41 // 根目录默认名称为首页. 42 return { 43 content: pathSection === '/' ? '业务受理' : curSection, 44 path: pathSection, 45 }; 46 }; 47 48 const routerList = getBreadcrumbs({ flattenRoutes: Routers, location: props.location})