优化字典 select 和 text

This commit is contained in:
sin 2019-03-15 22:59:37 +08:00
parent 888151f523
commit 70b5ea48b3
19 changed files with 184 additions and 216 deletions

View File

@ -44,8 +44,8 @@ function getDictionaryText(req, res) {
return res.json(resultBody(values)); return res.json(resultBody(values));
} }
function getDictionaryList(req, res) { function getDictionaryTree(req, res) {
return res.json(dictionaryList); return res.json(dictionaryList);
} }
export default { export default {
@ -54,7 +54,5 @@ export default {
'GET /admin-api/admins/resource/tree': getResourceTree, 'GET /admin-api/admins/resource/tree': getResourceTree,
'GET /admin-api/admins/role/page': getQueryRole, 'GET /admin-api/admins/role/page': getQueryRole,
'GET /admin-api/admins/admin/page': getQueryRole, 'GET /admin-api/admins/admin/page': getQueryRole,
'GET /admin-api/admins/dictionary/getList': getDictionaryKeys, 'GET /admin-api/admins/data_dict/tree': getDictionaryTree,
'GET /admin-api/admins/dictionary/queryText': getDictionaryText,
// 'GET /admin-api/admins/data_dict/list': getDictionaryList,
}; };

View File

@ -3,20 +3,17 @@
"message": "", "message": "",
"data": [ "data": [
{ {
"id": 1,
"enumValue": "gender", "enumValue": "gender",
"value": "1", "values": [
"displayName": "男", {
"sort": 1, "displayName": "男",
"memo": "性别 - 男" "value": 1
}, },
{ {
"id": 2, "displayName": "女",
"enumValue": "gender", "value": 2
"value": "2", }
"displayName": "女", ]
"sort": 2,
"memo": "性别 - 女"
} }
] ]
} }

View File

@ -0,0 +1,6 @@
import React from 'react';
// 字典全局的 Context会提前初始化工作。
const DictionaryContext = React.createContext({});
export default DictionaryContext;

View File

@ -1,13 +1,9 @@
import * as React from 'react'; import * as React from 'react';
import { Select } from 'antd'; import { Select } from 'antd';
export interface DictionaryObject {
text?: string;
value?: string | number | boolean;
}
export interface IDictionarySelectProps extends Select { export interface IDictionarySelectProps extends Select {
list?: DictionaryObject[]; dicKey?: string;
defaultValue?: string | number | boolean;
} }
export default class DictionarySelectD extends React.Component<IDictionarySelectProps, any> {} export default class DictionarySelectD extends React.Component<IDictionarySelectProps, any> {}

View File

@ -1,20 +1,32 @@
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import { Select } from 'antd'; import { Select } from 'antd';
import DictionaryContext from './DictionaryContext';
export default class DictionarySelect extends PureComponent { export default class DictionarySelect extends PureComponent {
renderOptions() { renderSelect(children) {
const { list } = this.props; return <Select {...this.props}>{children}</Select>;
return list.map(item => {
return (
<Select.Option key={item.value} value={item.value}>
{item.text}
</Select.Option>
);
});
} }
render() { render() {
const options = this.renderOptions(); const { dicKey } = this.props;
return <Select {...this.props}>{options}</Select>; return (
<DictionaryContext.Consumer>
{context => {
const dicValues = context[dicKey];
let nodes = [];
if (dicValues) {
nodes = Object.keys(dicValues).map(value => {
const text = dicValues[value];
return (
<Select.Option key={value} value={value}>
{text}
</Select.Option>
);
});
}
return this.renderSelect(nodes);
}}
</DictionaryContext.Consumer>
);
} }
} }

View File

@ -7,18 +7,15 @@ subtitle: 描述列表
## API ## API
### DescriptionList ### DictionarySelect
| 参数 | 说明 | 类型 | 默认值 | | 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------| |----------|------------------------------------------|-------------|-------|
| list | 数据列表 | DictionObject[] | [] | | dicKey | 字典key值 | string[] | [] |
| defaultValue | 来自 antd Select组件 | string、number、boolean | [] |
### DictionObject
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| text | 显示的文字 | string | - |
| value | 选择后的值 | string number boolean | - |
### Demo
```jsx harmony
<DictionarySelect dicKey="gender" defaultValue="1" />
```

View File

@ -0,0 +1,9 @@
import * as React from 'react';
import { Select } from 'antd';
export interface IDictionaryTextProps extends Select {
dicKey?: string;
dicValue?: string | number | boolean | Array<string | number | boolean>;
}
export default class DictionaryText extends React.Component<IDictionaryTextProps, any> {}

View File

@ -0,0 +1,21 @@
import React, { PureComponent } from 'react';
import DictionaryContext from './DictionaryContext';
export default class DictionaryText extends PureComponent {
componentDidMount() {}
render() {
const { dicKey, dicValue } = this.props;
return (
<DictionaryContext.Consumer>
{context => {
const dicValues = context[dicKey];
if (dicValues) {
return dicValues[dicValue];
}
return null;
}}
</DictionaryContext.Consumer>
);
}
}

View File

@ -1,5 +1,5 @@
--- ---
title: DictionaryValueText title: DictionaryText
subtitle: 获取字典 value 显示值 subtitle: 获取字典 value 显示值
--- ---
@ -9,11 +9,11 @@ subtitle: 获取字典 value 显示值
| 参数 | 说明 | 类型 | 默认值 | | 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------| |----------|------------------------------------------|-------------|-------|
| dataKey | 字典的key | string | [] | | dicKey | 字典的key | string | [] |
| value | 显示的值 | string number | [] | | dicValue | value值 | string、number、boolean | [] |
### Demo ### Demo
```jsx harmony ```jsx harmony
<DictionaryValueText dataKey="gender" value="1" /> <DictionaryValueText dicKey="gender" dicValue="2"/>
``` ```

View File

@ -16,6 +16,7 @@ import Exception403 from '../pages/Exception/403';
import PageLoading from '@/components/PageLoading'; import PageLoading from '@/components/PageLoading';
import SiderMenu from '@/components/SiderMenu'; import SiderMenu from '@/components/SiderMenu';
import getPageTitle from '@/utils/getPageTitle'; import getPageTitle from '@/utils/getPageTitle';
import DictionaryContext from '@/components/Dictionary/DictionaryContext';
import styles from './BasicLayout.less'; import styles from './BasicLayout.less';
// lazy load SettingDrawer // lazy load SettingDrawer
@ -68,6 +69,10 @@ class BasicLayout extends React.Component {
type: 'menu/getMenuData', type: 'menu/getMenuData',
payload: { routes, authority }, payload: { routes, authority },
}); });
dispatch({
type: 'dictionaryContext/tree',
payload: {},
});
} }
getContext() { getContext() {
@ -81,10 +86,17 @@ class BasicLayout extends React.Component {
getUrlsContext() { getUrlsContext() {
const { urlsData } = this.props; const { urlsData } = this.props;
return { return {
...urlsData, urls: {
...urlsData,
},
}; };
} }
getDictionaryContext() {
const { dicTreeMap } = this.props;
return dicTreeMap;
}
getRouteAuthority = (pathname, routeData) => { getRouteAuthority = (pathname, routeData) => {
const routes = routeData.slice(); // clone const routes = routeData.slice(); // clone
@ -178,7 +190,7 @@ class BasicLayout extends React.Component {
/> />
<Content className={styles.content} style={contentStyle}> <Content className={styles.content} style={contentStyle}>
<Authorized authority={routerConfig} noMatch={<Exception403 />}> <Authorized authority={routerConfig} noMatch={<Exception403 />}>
<UrlsContext.Provider values={this.getUrlsContext()}>{children}</UrlsContext.Provider> {children}
</Authorized> </Authorized>
</Content> </Content>
<Footer /> <Footer />
@ -191,7 +203,11 @@ class BasicLayout extends React.Component {
<ContainerQuery query={query}> <ContainerQuery query={query}>
{params => ( {params => (
<Context.Provider value={this.getContext()}> <Context.Provider value={this.getContext()}>
<div className={classNames(params)}>{layout}</div> <UrlsContext.Provider value={this.getUrlsContext()}>
<DictionaryContext.Provider value={this.getDictionaryContext()}>
<div className={classNames(params)}>{layout}</div>
</DictionaryContext.Provider>
</UrlsContext.Provider>
</Context.Provider> </Context.Provider>
)} )}
</ContainerQuery> </ContainerQuery>
@ -202,12 +218,13 @@ class BasicLayout extends React.Component {
} }
} }
export default connect(({ global, setting, menu: menuModel }) => ({ export default connect(({ global, setting, dictionaryContext, menu: menuModel }) => ({
collapsed: global.collapsed, collapsed: global.collapsed,
layout: setting.layout, layout: setting.layout,
menuData: menuModel.menuData, menuData: menuModel.menuData,
urlsData: menuModel.urlsData, urlsData: menuModel.urlsData,
breadcrumbNameMap: menuModel.breadcrumbNameMap, breadcrumbNameMap: menuModel.breadcrumbNameMap,
dicTreeMap: dictionaryContext.dicTreeMap,
...setting, ...setting,
}))(props => ( }))(props => (
<Media query="(max-width: 599px)"> <Media query="(max-width: 599px)">

View File

@ -1,6 +1,3 @@
import React from 'react'; import { createContext } from 'react';
// 创建全局的权限控制 context方便在所有页面使用 export default createContext();
const UrlsContext = React.createContext({});
export default UrlsContext;

View File

@ -0,0 +1,47 @@
import { dictionaryTree } from '../../services/admin';
export default {
namespace: 'dictionaryContext',
state: {
dicTree: [],
dicTreeMap: {},
},
effects: {
*tree({ payload }, { call, put }) {
const response = yield call(dictionaryTree, payload);
const dicList = response.data;
const dicTreeMap = {};
dicList.map(item => {
const dicKey = item.enumValue;
const dicTreeItem = {};
item.values.map(item2 => {
dicTreeItem.text = item2.displayName;
dicTreeItem.value = item2.value;
return true;
});
dicTreeMap[dicKey] = dicTreeItem;
return true;
});
yield put({
type: 'treeSuccess',
payload: {
dicTree: dicList,
dicTreeMap,
},
});
},
},
reducers: {
treeSuccess(state, { payload }) {
return {
...state,
...payload,
};
},
},
};

View File

@ -1,40 +0,0 @@
import { queryKey, queryText } from '../../services/dictionary';
export default {
namespace: 'dictionarySelect',
state: {
list: [],
text: '',
},
effects: {
*query({ payload }, { call, put }) {
const response = yield call(queryKey, payload);
yield put({
type: 'querySuccess',
payload: {
list: response.list,
},
});
},
*queryText({ payload }, { call, put }) {
const response = yield call(queryText, payload);
yield put({
type: 'querySuccess',
payload: {
text: response.text,
},
});
},
},
reducers: {
querySuccess(state, { payload }) {
return {
...state,
...payload,
};
},
},
};

View File

@ -1,26 +0,0 @@
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import DictionarySelect from '../../components/Dictionary/DictionarySelect';
@connect(({ dictionarySelect, loading }) => ({
data: dictionarySelect,
loading: loading.models.dictionarySelect,
}))
class DictionaryValueSelect extends PureComponent {
componentDidMount() {
const { dataKey, dispatch } = this.props;
dispatch({
type: 'dictionarySelect/query',
payload: {
dataKey,
},
});
}
render() {
const { data } = this.props;
return <DictionarySelect {...this.props} list={data.list} />;
}
}
export default DictionaryValueSelect;

View File

@ -1,19 +0,0 @@
---
title: DictionaryValueSelect
subtitle: 字典 value 选择
---
次组件跟使用 Antd extends Select使用方法跟 Select 一样
## API
### DescriptionList
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| dataKey | 字典的key | string | [] |
### Demo
```jsx harmony
<DictionaryValueSelect dataKey="gender" defaultValue={1} />
```

View File

@ -1,26 +0,0 @@
import React, { PureComponent } from 'react';
import { connect } from 'dva';
@connect(({ dictionarySelect, loading }) => ({
data: dictionarySelect,
loading: loading.models.dictionarySelect,
}))
class DictionaryValueText extends PureComponent {
componentDidMount() {
const { dataKey, dispatch } = this.props;
dispatch({
type: 'dictionarySelect/queryText',
payload: {
dataKey,
value: 1,
},
});
}
render() {
const { data } = this.props;
return <span>{data.text}</span>;
}
}
export default DictionaryValueText;

View File

@ -1,33 +1,23 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { Button } from 'antd'; import { Button } from 'antd';
import AuthorityControl from '../../components/AuthorityControl'; import DictionarySelect from '@/components/Dictionary/DictionarySelect';
import UrlsContext from '../../layouts/UrlsContext'; import DictionaryText from '@/components/Dictionary/DictionaryText';
import DictionaryValueSelect from '../Dictionary/DictionaryValueSelect'; import AuthorityControl from '@/components/AuthorityControl';
import DictionaryValueText from '../Dictionary/DictionaryValueText';
export default class Home extends Component { export default class Home extends Component {
state = {}; state = {};
render() { render() {
// 定义认证的属性 TODO
const GlobalAuthorityProps = {
user: 'admin',
login: 'success',
authList: {
'auth.button': true,
},
};
return ( return (
<UrlsContext.Provider value={GlobalAuthorityProps}> <div>
<AuthorityControl authKey="home.button"> <AuthorityControl authKey="home.button">
<Button type="primary">按钮 控制</Button> <Button type="primary">按钮 控制</Button>
</AuthorityControl> </AuthorityControl>
<h1>home...</h1> <h1>home...</h1>
<DictionaryValueSelect dataKey="gender" defaultValue={1} />
<DictionaryValueText dataKey="gender" value="1" /> <DictionarySelect dicKey="gender" defaultValue="1" />
</UrlsContext.Provider> <DictionaryText dicKey="gender" dicValue="2" />
</div>
); );
} }
} }

View File

@ -125,28 +125,34 @@ export async function roleAssignResource(params) {
// dictionary // dictionary
export async function dictionaryTree(params) {
return request(`/admin-api/admins/data_dict/tree?${stringify(params)}`, {
method: 'GET',
});
}
export async function dictionaryList(params) { export async function dictionaryList(params) {
return request(`/admin-api/admins/data_dict/list?${stringify(params)}`, { return request(`/admin-api/admins/data_dict/list?${stringify(params)}`, {
method: 'GET', method: 'GET',
}); });
} }
export async function dictionaryAdd(params) { export async function dictionaryAdd(params) {
return request(`/admin-api/admins/data_dict/add?${stringify(params)}`, { return request(`/admin-api/admins/data_dict/add?${stringify(params)}`, {
method: 'POST', method: 'POST',
body: {}, body: {},
}); });
} }
export async function dictionaryUpdate(params) { export async function dictionaryUpdate(params) {
return request(`/admin-api/admins/data_dict/update?${stringify(params)}`, { return request(`/admin-api/admins/data_dict/update?${stringify(params)}`, {
method: 'POST', method: 'POST',
body: {}, body: {},
}); });
} }
export async function dictionaryDelete(params) { export async function dictionaryDelete(params) {
return request(`/admin-api/admins/data_dict/delete?${stringify(params)}`, { return request(`/admin-api/admins/data_dict/delete?${stringify(params)}`, {
method: 'POST', method: 'POST',
}); });
} }

View File

@ -1,14 +0,0 @@
import { stringify } from '@/utils/request.qs';
import request from '@/utils/request';
export async function queryKey(params) {
return request(`/admin-api/admins/dictionary/getList?${stringify(params)}`, {
method: 'GET',
});
}
export async function queryText(params) {
return request(`/admin-api/admins/dictionary/queryText?${stringify(params)}`, {
method: 'GET',
});
}