antd pro中如何使用mock數據以及調用接口

antd pro的底層基礎框架使用的是dva,dva採用effect的方式來管理同步化異步json

在dva中主要分爲3層 services  models  componentsapi

models層用於存放數據以及對數據進行操做,services層調用請求後臺接口的方法,components層用於書寫頁面邏輯代碼服務器

services層antd

import request from '@/utils/request';app

export async function doit(payload) {cors

  const {id} = payload;框架

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

  return request(url,{async

    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數據主要包括如下幾步:

一、添加mock接口

二、添加service文件

三、添加model(需引入service函數)

四、頁面連接model

五、頁面調用model中的effect函數

六、model中的effects經過reducer中的函數將數據返回到頁面

七、頁面經過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: '網關超時。', }
相關文章
相關標籤/搜索