首先简要的介绍一下问题,我们公司大部分项目都是使用umi+Ant Design Pro 构建(下面的Pro都指代它),因为场景的不同,我们总是要根据不同的场景区分和抽离布局组件,在Pro中的layouts文件夹里面已经为我们提供了不同场景的布局组件。
大部分页面包含了通用的导航、侧边栏、顶部通知、页面标题等元素,这时候我们会使用BasicLayout
作为布局组件,使用如下:
{
path: '/org',
component: '../layouts/SecurityLayout',
routes: [
{
path: '/',
component: '../layouts/BasicLayout',
authority: [],
routes: [
{
path: '/org/dashboard',
name: 'dashboard',
component: './dashboard'
},
{
path: '/org/department',
name: 'department',
component: './department',
hideInMenu: true
},
{
path: '/org/user',
name: 'user',
component: './user/list'
},
{
component: './404'
}
]
}
]
},
这时候问题就出现了,/org/department
页面的布局不是BasicLayout
,而是BlankLayout
。那怎么办?
刚开始这种页面不多,直接就在BasicLayout中的render函数中判断location.pathname的值,直接return一个children,代码如下:
if (['/org/department'].indexOf(pathname) > -1) {
return <div>{children}</div>
}
从此不优雅的代码开始疯狂的增长,想象一下当有十几个页面出现这种情况的时候。
下面我们就用装饰器模式,优雅的解决这个问题。如果对装饰器比较陌生的同学可以看这里Javascript 中的装饰器
先实现一个装饰器,一个高阶组件ExcludeLayout
:
import React, { Component } from 'react';
import BlankLayout from './BlankLayout';
function ExcludeLayout(opt) {
return function(WrappedComponent) {
return class extends Component {
render() {
const {
children,
location = {
pathname: '',
},
} = this.props;
const { routes } = opt;
const { pathname } = location;
if (routes.indexOf(pathname) > -1) {
return <BlankLayout {...this.props} />
}
return (
<WrappedComponent {...this.props} />
);
}
}
}
}
export default ExcludeLayout;
上面这个高阶函数其实就是进行路由的挟持,如果pathname
在我们传入的opt.routes
路由数组中,我们就使用BlankLayout
布局组件。下面看一下ExcludeLayout
装饰器去装饰BasicLayout
组件:
@ExcludeLayout({
routes: ['/org/department']
})
class BasicLayout extends Component {
.......
.......
}
// 非class定义的使用
BasicLayout = ExcludeLayout({
routes: [`/org/department`]
})(BasicLayout);
以上就用装饰模式,优雅的解决上面的问题。
实际开发场景下还有很多地方可以用到装饰器,当代码写好看起来就讨厌的时候,就可以思考思考是否有上面优雅的实现方式。
网友评论