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


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: '網關超時。', }

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM