15-2 RN之发现页面的model

82 阅读1分钟

在这一节中,我们将创建发现模块的 Model,并了解其数据结构。以下是实现步骤:

一、数据结构

  1. 接口地址/mock/11/bear/found/list

  2. 接口数据

    {
      "status": 100,
      "msg": "success",
      "data": [
        {
          "id": "5f9c397d-4f8e-4a1c-8b2b-1c3d4e5f6a7b",
          "title": "神秘的深海世界",
          "videoUrl": "https://www.runoob.com/try/demo_source/mov_bbb.mp4"
        },
        {
          "id": "5f9c397d-4f8e-4a1c-8b2b-1c3d4e5f6a7c",
          "title": "深海探险:设备篇",
          "videoUrl": "https://www.runoob.com/try/demo_source/mov_bbb.mp4"
        }
      ]
    }
    

二、创建 Model

  1. 创建 found.tsx 文件

    models 文件夹下创建 found.tsx 文件:

    import { Model, Effect } from 'dva-core-ts';
    import axios from 'axios';
    
    const REQUEST_URL = '/mock/11/bear/found/list';
    
    export interface IFound {
      id: string;
      title: string;
      videoUrl: string;
    }
    
    interface FoundModel extends Model {
      namespace: 'found';
      effects: {
        fetchList: Effect;
      };
    }
    
    const foundModel: FoundModel = {
      namespace: 'found',
      state: {},
      effects: {
        *fetchList({ callback }, { call }) {
          const { data }: { data: IFound[] } = yield call(axios.get, REQUEST_URL);
          if (typeof callback === 'function') {
            callback(data);
          }
        },
      },
    };
    
    export default foundModel;
    
  2. 更新 models/index.ts 文件

    models/index.ts 文件中添加 found 模型:

    import found from './found';
    
    const models = [found];
    
    export type RootState = {
      found: typeof found.state;
    };
    

三、总结

在本节中,我们创建了发现模块的 Model,并定义了数据结构。通过使用 dvaeffects,我们实现了数据的异步加载。下一节,我们将完成发现页面的 UI 实现。