1. 新增 models 目录
项目规定,src/models
下定义项目的 models
层数据。
/*
* @Description: global 模块 models 层
* @Author: kivet
* @Date: 2022-01-13 17:21:33
* @LastEditTime: 2022-01-26 10:32:21
*/
import type { Effect, ImmerReducer, Subscription } from 'umi';
import { getDeviceList } from '@/services/global';
import { DruidLocalStorage } from '@/utils/storage';
import { StorageEnum } from '@/utils/enum';
import { Helper } from '@/utils/helper';
export interface IGlobalModelState {
/** 设备列表数据 */
deviceList: any[];
}
export interface IGlobalModelType {
namespace: 'global';
state: IGlobalModelState;
effects: {
/** 获取设备列表数据 */
getDeviceList: Effect;
};
reducers: {
updateState: ImmerReducer<IGlobalModelType>;
};
subscriptions: {
setup: Subscription;
};
}
const GlobalModel: IGlobalModelType = {
namespace: 'global',
state: {
deviceList: [],
},
effects: {
*getDeviceList({ payload, callback }, { call, put }) {
const data = yield call(getDeviceList, payload) || [];
yield put(Helper.createAction('updateState')({ deviceList: data }));
callback && data.length && callback(data);
},
},
reducers: {
updateState(state, { payload }) {
return {
...state,
...payload,
};
},
},
subscriptions: {
setup({ history }) {
history.listen(({ pathname }) => {
if (
pathname !== '/login' &&
!DruidLocalStorage.get(StorageEnum.TOKEN)
) {
// Helper.handleRedirect(); // ? 没有登录功能,暂时屏蔽不重定向
}
});
},
},
};
export default GlobalModel;
2. 新增 services 目录
项目规定,src/services
下定义项目的 services
层数据。
/*
* @Description: global 模块 services 层
* @Author: kivet
* @Date: 2022-01-13 17:19:47
* @LastEditTime: 2022-01-26 10:34:10
*/
import request from '@/utils/request';
/** 获取设备列表数据 */
export const getDeviceList = async () =>
request('/device/page/', {
method: 'GET',
data: {},
headers: {
'x-result-limit': '50',
'x-result-sort': '-_id',
},
});
这里的 request
是全局封装的一个请求/响应拦截器,具体可访问链接
3. 测试
随便找个文件使用,调取上面写的 API demo
import { FC, useEffect, useState } from 'react';
import { Button, Input } from 'antd';
import { DruidLocalStorage } from '@/utils/storage';
import {
connect,
Dispatch,
IGlobalModelState,
Loading,
ConnectProps,
} from 'umi';
import styles from './index.less';
interface IProps extends ConnectProps {
dispatch: Dispatch;
global: IGlobalModelState;
loading: boolean;
}
const IndexPage: FC<IProps> = (props) => {
const { dispatch, global, loading = false } = props;
useEffect(() => {
dispatch({
type: 'global/getDeviceList',
});
}, []);
return (
<div>
{global.deviceList.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default connect(
({ global, loading }: { global: IGlobalModelState; loading: Loading }) => ({
global,
loading: loading.models.global,
}),
)(IndexPage);
如果不配置 API 的地址,项目就会默认走 mock,可将本地 API_BASE
值置改成空串
测试结果,如果通过 props.global.deviceList
能拿到 mock 的数据,说明成功了。
[0] Dva 和 umi 的简单介绍