/*
* @Author: zhudongguang
* @Date: 2022-02-16 14:47:49
* @LastEditTime: 2022-03-03 12:35:49
* @数据流向为 页面 dispath ==> Service ==> Effects ==> Reducers ==> 页面
*/
// const model = {
// namespace: '', model的命名空间
// state: {}, 初始仓库
// reducers: {}, 处理同步数据的函数
// effects: {}, 处理异步数据的函数
// Subscription: {}, 订阅数据源
// };
// export default model;
import { Effect, ImmerReducer, Subscription } from 'umi';
import * as namespaces from '@/constants/namespaces';
export interface DemoModalState {
name: string;
}
export interface DemoModelType {
// namespace命名空间,相当于给model取个名字,但是各个model的namespce是不能重复的
namespace: string;
// state是数据仓库,就是存数据的地方,model里的数据都是存放在这里的
state: DemoModalState;
// 异步方法,简单来说我们的异步请求就写在这里
effects?: {
query?: Effect;
asyncGetData: Effect;
};
// reducers把数据存到仓库(存到state)里的唯一方法,我们修改state里的数据不能直接像this.name='liu'这样去修改,而必须通过调用reducers里的方法
reducers: {
save: ImmerReducer<DemoModalState>;
// state 为上次state的值,action 为触发payload中的值
getList: (state: DemoModalState, action: any) => any;
};
// 订阅,比如监听页面,监听到进入了某某页面就让它执行相关代码之类的
subscriptions: { setup: Subscription };
}
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['loser'],
},
];
const DemoModel: DemoModelType = {
namespace: namespaces.DEMO,
state: {
name: '',
},
effects: {
// *query({payload}, {call put}) {},
*asyncGetData(action, effects) {
const listData = yield Promise.resolve(data);
// 如果想用实际接口拿到数据需要调用call
// const { data } = yield effects.call(remoteApi)
// 用effects.put 把数据推给reducers, 并触发getList 函数
yield effects.put({ type: 'getList', payload: listData });
},
},
reducers: {
save(state, action) {
state.name = action.payload;
},
getList(state, action) {
return { listData: action.payload };
},
},
subscriptions: {
setup({ dispatch, history }) {
// dispatch({ type: 'asyncGetData' });
// return history.listen(({ pathname }) => {
// if(pathname === '/home') {
// dispatch({ type: 'demo/getList' })
// }
// })
},
},
};
export default DemoModel;