How to call mock data in Umi

Keywords: axios Spring npm TypeScript

Official website

According to the official website, you can download it by executing yar create umi or npm create umi.
After that, select: the space is select enter is OK
Select project = > select app

Choose whether to use TypeScript.

Then, select the function you need = = > antd + DVA

OK, the basic shelf has been selected. Next, start to use your own mock data.

1. New mock data

Create a new file heroList.js under the mock file to save the mock data

**const heroList = {
  status: 'ok',
  code: '200',
  list: [
    [
      {
        label: '2013',
        value: '2013',
      },
      {
        label: '2014',
        value: '2014',
      },
    ],
    [
      {
        label: 'spring',
        value: 'spring',
      },
      {
        label: 'summer',
        value: 'summer',
      },
    ],
  ]
}

export default {
  'GET /appservice/common/v1/getBusinessList': heroList
}**

2. Call data

The path is pages/index

  1. Introduce connect
import { connect } from 'dva';
  1. Define listening interface name
@connect(({ loading }) => ({
  loading: loading.effects['index/getHeroList']
}))

I haven't created models yet, but I can define the interface name first.

  1. call
  componentDidMount () {
    this.getHeroList()
  }

  getHeroList = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'index/getHeroList'
    }).then((res) => {
      console.log(res)
      this.setState({
        HeroList: res.list
      })
    })
  }

OK, now it's time to create the data in the models

3. Create models

The directory is / pages/index/models/index

import { getHeroListSer } from '@/server/S_index'

export default {
  namespace: 'index',
  state: {
  },

  effects: {
    *getHeroList({ payload }, { call }) {
      console.log('666')
      const response = yield call(getHeroListSer, payload)
      console.log(response)
      return response;
    }
  },
  
  reducers: {
  }

}

getHeroListSer is encapsulated by calling interface, so we will continue to create new one here.

4. Create js for collective request

import { HTTP } from '@/utils/creatApi'

export const getHeroListSer = HTTP('/appservice/common/v1/getBusinessList', 'GET')

5. Create Http to initiate request and return data

import { request } from '@/utils/quest'
import { stringify } from 'qs'


//External interface
export function HTTP(url, METHOD = 'GET'){

  return async function h(params) {
    switch(METHOD.toUpperCase()) {
      case 'GET':
      return request.GET(`${url}${stringify(params)}`);
      case 'POST':
      return request.POST(`${url}`, params);
      default:
      break;
    }
  }
}

6. Encapsulation request method

import axios from 'axios'
import { stringify } from 'qs'


//Set timeout
axios.defaults.timeout = 10000;
// post request header
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

export const request = {
  GET: function(url) {
    return new Promise((resolve, reject) =>{
        axios.get(url).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
  },
  POST: function(url, params) {
    return new Promise((resolve, reject) =>{
        axios.post(url, stringify(params)).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
          
    });
  }
}


// Response interceptor (processing response data)
axios.interceptors.response.use( 
  response => {
    console.log(response.data.code)
      if(response.data.code == '200'){
          return Promise.resolve(response);
      }else{
          //In this place, the background editing status code can distinguish different situations and do different logical processing.
          return Promise.reject(response);
      }
  },
  error => {
      // //If the request fails, some interface logic can be uniformly processed according to error.response.status. For example, if status is 401, it can be redirected.
      // router.replace({      
      //     path: '/login',      
      //     query: { redirect: router.currentRoute.fullPath } 
      //    });
      return Promise.reject(error.response);  

  }
)

github address

Posted by secret007 on Fri, 01 Nov 2019 20:58:52 -0700