10-3 分类模块的model

132 阅读1分钟

在本节中,我们将学习如何在应用加载时请求类别接口,并将数据保存到本地存储中。以下是分类模块的 Model 实现:

一、创建分类模块的 Model

1. 创建 category.ts 文件

models 文件夹下创建 category.ts 文件:

import { Model, Effect, Reducer, SubscriptionsMapObject } from 'dva-core-ts';
import { ICategory } from '@/interfaces/category';
import storage from '@/config/storage';

export interface CategoryModelState {
  categorys: ICategory[];
  myCategorys: ICategory[];
}

export interface CategoryModel extends Model {
  namespace: 'category';
  state: CategoryModelState;
  effects: {
    loadData: Effect;
  };
  reducers: {
    setState: Reducer<CategoryModelState>;
  };
  subscriptions: SubscriptionsMapObject;
}

const initialState: CategoryModelState = {
  myCategorys: [
    {
      id: 'home',
      name: '推荐',
    },
    {
      id: 'vip',
      name: 'VIP',
    },
  ],
  categorys: [],
};

const categoryModel: CategoryModel = {
  namespace: 'category',
  state: initialState,
  reducers: {
    setState(state = initialState, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    *loadData(_, { call, put }) {
      const categorys: ICategory[] = yield call(storage.load, {
        key: 'categorys',
      });
      const myCategorys: ICategory[] = yield call(storage.load, {
        key: 'myCategorys',
      });
      let payload;
      if (myCategorys) {
        payload = {
          myCategorys,
          categorys,
        };
      } else {
        payload = {
          categorys,
        };
      }
      yield put({
        type: 'setState',
        payload,
      });
    },
  },
  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'loadData' });
    },
  },
};

export default categoryModel;

2. 配置 storage.ts

config 文件夹中创建 storage.ts 文件:

import AsyncStorage from '@react-native-community/async-storage';
import Storage, { LoadParams } from 'react-native-storage';

const storage = new Storage({
  size: 1000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24 * 7,
  enableCache: true,
  sync: {
    categorys: async () => {
      const { data } = await axios.get('/mock/11/bear/category');
      return data;
    },
    myCategorys: async () => {
      const data = [
        {
          id: 'home',
          name: '推荐',
        },
        {
          id: 'vip',
          name: 'VIP',
        },
      ];
      return data;
    },
  },
});

const load = (params: LoadParams) => {
  return new Promise((resolve, reject) => {
    storage
      .load(params)
      .then((ret) => {
        resolve(ret);
      })
      .catch((err) => {
        console.log(err);
        reject(err);
      });
  });
};

export { load };
export default storage;

3. 更新 models/index.ts

models/index.ts 中添加 category 模块:

import home from './home';
import category from './category';

export const models = [home, category];

export type RootState = {
  home: typeof home.state;
  category: typeof category.state;
};

二、总结

在本节中,我们创建了分类模块的 Model,实现了数据的加载和本地存储的同步。通过使用 dvasubscriptions 功能,我们在应用加载时自动请求类别接口,并将数据保存到本地存储中。下一节,我们将完成分类页面的基本布局和样式。