model.ts 1.9 KB
Newer Older
1
import { queryFakeList, removeFakeList, addFakeList, updateFakeList } from './service';
陈帅's avatar
陈帅 committed
2 3 4 5
import { BasicListItemDataType } from './data';
import { Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { AnyAction } from 'redux';
6

陈帅's avatar
陈帅 committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
export interface IStateType {
  list: BasicListItemDataType[];
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: IStateType) => T) => T }
) => void;

export interface ModelType {
  namespace: string;
  state: IStateType;
  effects: {
    fetch: Effect;
    appendFetch: Effect;
    submit: Effect;
  };
  reducers: {
    queryList: Reducer<IStateType>;
    appendList: Reducer<IStateType>;
  };
}

const Model: ModelType = {
31
  namespace: 'BLOCK_NAME_CAMEL_CASE',
32 33 34 35 36 37

  state: {
    list: [],
  },

  effects: {
afc163's avatar
afc163 committed
38
    *fetch({ payload }, { call, put }) {
39 40 41 42 43 44
      const response = yield call(queryFakeList, payload);
      yield put({
        type: 'queryList',
        payload: Array.isArray(response) ? response : [],
      });
    },
JoeyKo's avatar
JoeyKo committed
45 46 47 48 49 50 51
    *appendFetch({ payload }, { call, put }) {
      const response = yield call(queryFakeList, payload);
      yield put({
        type: 'appendList',
        payload: Array.isArray(response) ? response : [],
      });
    },
valleykid's avatar
valleykid committed
52 53 54 55 56 57 58 59
    *submit({ payload }, { call, put }) {
      let callback;
      if (payload.id) {
        callback = Object.keys(payload).length === 1 ? removeFakeList : updateFakeList;
      } else {
        callback = addFakeList;
      }
      const response = yield call(callback, payload); // post
60
      yield put({
valleykid's avatar
valleykid committed
61 62
        type: 'queryList',
        payload: response,
63 64 65 66 67
      });
    },
  },

  reducers: {
68 69 70 71 72 73
    queryList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
陈帅's avatar
陈帅 committed
74
    appendList(state = { list: [] }, action) {
JoeyKo's avatar
JoeyKo committed
75 76 77 78 79
      return {
        ...state,
        list: state.list.concat(action.payload),
      };
    },
80 81
  },
};
陈帅's avatar
陈帅 committed
82 83

export default Model;