Call api Interface & mock local data | dva

Details Reference: DvaJS

Call api Interface


To invoke cnodethe interface as an example

The first step: Edit the .webpackrcfile

Add to:

"proxy": {
  "/apis": {
    "target": "目标 API 接口",
    "changeOrigin": true,
    "pathRewrite": {"^/apis": ""}   // 可省...
  }
}

Configuration agent, transferred through the interface

Step 2: Edit services/example.jsthe file

import request from '../utils/request';

const pox = "/apis/"
export function testCnode() {
  return request(pox + '/api/v1/topics');
}

Step Three: Call Interface

1. Use interface component

import  * as apis from '../services/example'

apis.testCnode().then((res) => {
  console.log(res)
})

2. In modeluse the interface
to

import * as apis from '../services/example'

export default {
  namespace: 'indexPage',
  state: {
     cnodeData: []
  },
 
  effects: {
    *testCnode(action, {put, call}) {
      let rel = yield call(apis.testCnode)
      if(rel.data) {
        yield put({
          type: 'setCnodeDataList',
          data: rel.data.data
        })
      }
    }
  },
  
  reducers: {
     setCnodeDataList(state, payload) {
      return {
        ...state,
        cnodeData: payload.data
      }
    }
  },
}

First introduced import * as apis from '../services/example',
in effectsthe asynchronous using call(apis.testCnode)call interface data,
to find the detailed data in put({data: 详细数据})use, as put({type: 对应的事件})the payloadvalue is passed reducersin 对应的事件
use in the assembly mapStateToPropscan get the data

mock local data


mock 数据不需要这么麻烦,直接在 reducers 中,把 json 格式的文件设置到 state 里面就可以

The first step: define the interface

In the mockfolder, create a testMock.jsfile, edit the file:

module.exports={
  "GET /api/mockdata": (req, res) => {
    console.log(req)
    res.send({
      msg: '登录成功'   // 为要 mock 的数据
    })
  }
}

Step Two: Registration Interface

Find .roadHogrc.mock.jsFile, Edit:

export default {
  ...require("./mock/testMock")
};

The third step: Request Interface

In services/example.jsthe request interface

export function mockdata() {
  return request("api/mockdata");
}

Step Four: Same as above using an interface

Published 23 original articles · won praise 0 · Views 569

Guess you like

Origin blog.csdn.net/JIANLI0123/article/details/103492581