antd pro的底层基础框架使用的是dva,dva采用effect的方式来管理同步化异步

在dva中主要分为3层 services  models  components

models层用于存放数据以及对数据进行操作,services层调用请求后台接口的方法,components层用于书写页面逻辑代码

services层

import request from '@/utils/request';

export async function doit(payload) {

  const {id} = payload;

  let url = `/api/v2/.../${id}`;

  return request(url,{

    mode: 'cors',

    method: 'GET',

  })

    .then(res => {

      return res;

    })

    .catch(err => console.log(err));

}

models层中的effects是与后台交互、处理数据逻辑的地方

import {doit} from '../../'

export default {

  namespace: 'test',

  effects: {

    *fetchNum ({payload,callback},{call,put}) {

      const res = yield call (doit,payload)

      //doit是引入services层那个js文件的doit方法,payload是后台要求传递的参数,res就是后台返过来的数据

      yield put ({

        type: 'addNum', //这就是reducer的addNum方法,put用来出发reducer中的方法,payload是传过去的参数。同时也能触发同等级effects中的方法

        payload: {

           num: res.data    //把后台返回的数据赋值给num,假如哪个reducer中的方法是由这里effects去触发的,哪个num名必须是这里的名字num,如果reducer中的方法不是这触发,那名字可以随意取

        }

      })

    }

  }

  reducers: {

    addNum (state,{payload:{num}}) {

      return {...state,num}

     }

  }

}

components层

页面如果需要使用models层的数据,要用connect进行连接,即在页面在引入import {connect} from 'dva';@connect(state => ({test:state.test})) 通过this.props获取数据

this.props.dispatch({

  type: 'test/fetchNum',   test对应models层的命名空间namespace

  payload: {

    numCount: ++1

  }

})

使用mock数据主要包括以下几步:

1、添加mock接口

2、添加service文件

3、添加model(需引入service函数)

4、页面链接model

5、页面调用model中的effect函数

6、model中的effects通过reducer中的函数将数据返回到页面

7、页面通过this.props获取数据

具体操作就是在项目根目录下,mock文件夹中新建record.js文件,用于存放mock数据

export default {
'GET /love/record':{
message: 'Succeed',
code:0,
data: [
{
key: '1',
Name: '违规操作',
age: '口腔科',
address: '人民医院',
tags: '2019-03-21 12:56:12',
questions: '温度'
},
{
key: '2',
Name: '违规操作',
age: '皮肤科',
address: '人民医院',
tags: '2019-03-21 12:56:12',
questions: '压力'
},
]
}
}

然后在src目录下的services文件夹中新建一个record.js文件,用来创建请求数据的函数,框架已经为我们封装好了request函数(可能需要我们对request.js文件进行补充),我们可以直接进行使用

import request from '../utils/request' ;
export async function getRecord (payload) {
return request('/love/record',{
//如果路径中有参数,需要用字符串模板进行拼接``
method: 'GET'
})
.then(res => {
return res;
}
.catch(err => console.log(err))
}

src目录下的models文件夹是store文件夹,用来定义state

新建record.js文件

引入我们在services文件夹中创建的请求数据的函数

import { getRecord } from '../services/record' ;
export default {
namespace: 'demo',
state:{
record: [],
},
  effects: {
   *getRecord(payload,{call,put}) {
   const res = yield call(getRecord,payload)
   yield put({
   type: 'updateToView',
   payload:{record:res.data}
   });
  }
  },
  reducers: {
   updateToView(state, { payload }) {
   return {
   ...state,
   ...payload,
   }
   }
  }
}

最后在page页面中,通过this.props就可以得到我们想要的数据

import { connect } from 'dva' ;
@connect(state=> ({
demo:state.demo
})
componentDidMount(){
const { dispatch } = this.props;
dispatch({
//需要调用对于namespace下effects中的该函数
type: 'record/getRecord',
})
}
console.log(this.props)就可以得到结果
const { demo } = this.props

我的request.js文件

import fetch from 'dva/fetch';
import { message } from 'antd';
import { error } from '@/utils/error';
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const errortext = error[response.status] || response.statusText;
let isLogin = response.url.search('/unsecure/login') != -1;
if (response.status === 401) {
if (isLogin) {
message.error(`请求错误 ${response.status}: ${errortext}`);
} else {
console.log('gogogo')
router.push('/user/login');
}
} else {
if (!isLogin) {
message.error(`请求错误 ${response.status}: ${errortext}`);
}
}
return response;
};
export default function request(url, option) {
//获取token
let token = localStorage.getItem('token');
const options = {
...option,
headers: {
'X-Authorization': token,
'x-language': 'chinese',
},
};
const newOptions = { ...options, credentials: 'include' };
if (
newOptions.method === 'POST' ||
newOptions.method === 'PUT' ||
newOptions.method === 'DELETE'
) {
if (!(newOptions.body instanceof FormData)) {
newOptions.headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
...newOptions.headers,
};
if (newOptions.dataType != 'string') {
newOptions.body = JSON.stringify(newOptions.body);
}
} else {
newOptions.headers = {
Accept: 'application/json',
...newOptions.headers,
};
}
}
return (
fetch(url, newOptions)
.then(checkStatus)
.then(response => {
if (newOptions.responseType === 'blob') {
return response.blob();
}
let type = typeof response;
switch (type) {
case 'object':
return response.json();
case 'string':
return response.text();
}
return response.json();
})
.then(res => {
return res;
})
.catch(e => { })
);
} error.js文件
export default {
 40101: '再输错两次将锁住',
 40200: '用户不存在',
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  401: '用户权限错误。',
  403: '权限信息错误。',
  404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维保。',
  504: '网关超时。',
}

  

antd pro中如何使用mock数据以及调用接口的更多相关文章

  1. yii中的restful方式输出并调用接口和判断用户是否登录状态

    //创建一个控制器接口 返回的是restful方式 <?php namespace frontend\controllers; use frontend\models\Fenlei; use f ...

  2. vue-cli3.x中使用axios发送请求,配合webpack中的devServer编写本地mock数据接口(get/post/put/delete)

    vue-cli3.x中使用axios发送请求,配合webpack中的devServer编写本地mock数据接口(get/post/put/delete) 手把手式笔记 Axios配置 安装 axios ...

  3. 强大的table组件-antd pro table

    概述 antd pro table antd pro table 的主要部分 表格显示的配置(绿色框内) 检索的配置(红色框内) 是否显示检索部分 检索的内容是如何生效的 工具栏的配置(黄色框内) 表 ...

  4. antd pro 路由

    概要 antd pro 路由简介 路由, 菜单和面包屑 页面之间的路由 带参数的路由 总结 概要 路由配置是单页应用的核心之一, antd pro 将所有的路由配置集中在一个文件中, 可以更好的对应用 ...

  5. antd pro table中的文件上传

    概述 示例代码 列表页面 form 页面 model.js service.js 总结 概述 项目中经常会遇到在表格中展示图片的需求(比如展示用户信息时, 有一列是用户的头像). antd pro t ...

  6. vue-cli项目中怎么mock数据

    在vue项目中, mock数据可以使用 node 的 express模块搭建服务 1. 在根目录下创建 test 目录, 用来存放模拟的 json 数据, 在 test 目录下创建模拟的数据 data ...

  7. GPS模块输出的NMEA数据ddmm.mmmm转换成dd.ddddd并在google Earth Pro中描点

      GPS模块输出的数据是NMEA格式,其中GPGGA字段包含我们需要的经纬度信息. 例:$GPGGA,092204.999,4250.5589,S,14718.5084,E,1,04,24.4,12 ...

  8. Electron-vue实战(三)— 如何在Vuex中管理Mock数据

    Electron-vue实战(三)— 如何在Vuex中管理Mock数据 作者:狐狸家的鱼 本文链接:Vuex管理Mock数据 GitHub:sueRimn 在vuex中管理mock数据 关于vuex的 ...

  9. mock 数据 解决方案

    前端工程化之--Mock解决方案   https://www.jianshu.com/p/720b12b5d120 一.为什么要使用mock数据: 1.后端接口数据没有的时候,前端根据接口文档,使用 ...

随机推荐

  1. Qt - 设置程序界面风格(现成的QMacStyle等等)

    类的继承关系: QMotifStyle:OSF(开放基金协会)开发的一个工业标准的GUI(图形用户接口): QCDEStyle:公共桌面环境(Common Desktop Environment)的缩 ...

  2. Qt 之 样式表的使用——样式选择器(上下篇,很详细)

    http://blog.csdn.net/goforwardtostep/article/details/60884870 http://blog.csdn.net/goforwardtostep/a ...

  3. 第四章 .net core做一个简单的登录

    项目目标部署环境:CentOS 7+ 项目技术点:.netcore2.0 + Autofac +webAPI + NHibernate5.1 + mysql5.6 + nginx 开源地址:https ...

  4. spark开发常见问题之一:java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.

    最近在学习研究pyspark机器学习算法,执行代码出现以下异常: 19/06/29 10:08:26 ERROR Shell: Failed to locate the winutils binary ...

  5. Kafka 学习之路(一)—— Kafka简介

    一.简介 Apache Kafka是一个分布式的流处理平台.它具有以下特点: 支持消息的发布和订阅,类似于RabbtMQ.ActiveMQ等消息队列: 支持数据实时处理: 能保证消息的可靠性投递: 支 ...

  6. pytorch实现yolov3(4) 非极大值抑制nms

    在上一篇里我们实现了forward函数.得到了prediction.此时预测出了特别多的box以及各种class probability,现在我们要从中过滤出我们最终的预测box. 理解了yolov3 ...

  7. sql语句的注意点

    select * from CallRecords where CallerNumber=001 and  TelNum=02088888881 or id=1; 如果  CallerNumber=0 ...

  8. TCP/IP协议与OSI体系结构总结

    什么是TCP/IP协议?TCP/IP协议不是一个简单的TCP和IP协议,而是个协议族的统称,是网络通信的一套协议集合. TCP/IP协议与OSI七层模型在模块分布上具有一定的区别,OSI参考模型通信协 ...

  9. Codeforces Gym101518H:No Smoking, Please(最小割)

    题目链接 题意 给出一个n*m的酒店,每个点是一个房间,要将这个酒店的房间划分成为两块(一块无烟区,一块吸烟区),相邻的两个房间之间有一条带权边,权值代表空气锁的面积,如果把这条边给去掉,那么需要花费 ...

  10. 对于Spring中AOP,DI,IoC概念的理解

    IOC IoC(inversion of Control),控制反转.就好像敏捷开发和SCRUM一样,不是什么技术,而是一种方法论,一种工程化的思想.使用IoC的思想意味着你将设计好的对象交给容器控制 ...