umi中mock数据

umi项目APPdva mock数据

1、首先在mock文件夹下新建js文件

export default{
    'post /api/user/login':{
        success:true,
        data:{
            loginCode:true
        },
        
    }
}

2、新建models文件夹,注意:全局的放在根目录在,但也可以不放在对应文件夹下面

  • url.js
let local=process.env.local || ''
console.log('=local==',local)
export default{
    login:`${local}/api/user/login`,//登录接口
    functionList:`${local}/api/functionList`,//功能列表接口
}
  • request.js
import Url from './url';
import fetch from 'dva/fetch';



function parseJSON(response) {
    return response.json();
  }
  
  function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
      return response;
    }
    if(response.status === 401 || response.status === 400){
      console.log(response)
    //   return  Api.logout('接口报错')
    }
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
  
  function customOptions(options) {  
    let newOptions = '';
    for (var key in options) {
      newOptions += `${key}=${options[key]}&`
    }
    return newOptions.slice(0, newOptions.length - 1);
  }

export default function request(url, options) {

  console.log(fetch)

    options = options || {}
    options.method = options.method ? options.method : 'POST';
  
    options.headers = options.headers || {};
    options.headers =  {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      ...options.headers
    }
    if(options.headers['Content-Type'].indexOf('/json') > -1){
      options.body = JSON.stringify(options.body)
    }else{
      options.body = customOptions(options.body);
    }
    
    // if(url !== Url.login){//登录接口增加特殊参数
    //   options.headers ={
    //     ...options.headers,
    //      "Authorization" : `Bearer ${Api._getCookie('userToken') || ''}`
    //   }
    // }
  
  
    if(options.method === 'GET'){
      let _getData = options.body ? `${url}?${options.body}` : url
      return fetch(_getData, {
        headers: options.headers,
        method: options.method,
      })
      .then(checkStatus)
      .then(parseJSON)
      .then(res =>  {
        if (res.success || res.errorCode === 0) {
          return res;
        } else {
        //   ErrorMessage(res,res.errorCode);
          return {}
        }
      })
      .catch(err =>{
        return err;
      });
    }else{
      return fetch(url, {
        headers: options.headers,
        method: options.method,
        body: options.body
      })
      .then(checkStatus)
      .then(parseJSON)
      .then(res => {
        if (res.success || res.errorCode === 0) {
          return res;
        } else {
        //   ErrorMessage(res,res.errorCode);
          return {}
        }
      })
      .catch(err => {
        return err;
      });
    }
  }
  • models下文件

import request from '../utils/request' //封装的接口请求,
import url from '../utils/url' //请求的地址
export default{
    namespace:'login',//命名空间名字
    state:{loginStatus:'登录失败'},//放置初始值
    subscriptions:{}, 订阅监听,比如我们监听路由,进入页面就如何,可以在这写
    effects:{
        *Login({ payload,history}, { call, put }){
            const res=yield call(request,url.login,{
                body:payload
            })
            console.log('===models=',history)
            console.log('===res=',res)
            yield put({ type: 'save', payload: { } } );
            console.log('=payload==',payload)
            if(res.data.loginCode===true){
                history.push('/functionList/functionList')
            }
        }
        
    },// 与后台交互,处理数据逻辑的地方
    reducers: {
        save(state,action){
            return{
            ...state,
            ...action
            }
            
        }
    }//函数接受两个参数:之前已经累积运算的结果和当前要被累积的值,返回的是一个新的累积结果。该函数把一个集合归并成一个单值。

}

3、在对应的组件中应用

import {connect} from 'dva'

function mapStateToProps(state){
  console.log('==state==',state)
  return{
    functionList:state.functionList
  }
}
//1、第一种
  getLogin=(e)=>{//点击登录
    console.log('====',history)
    console.log(this.props)
    this.props.dispatch({
      type:'login/Login',//命名空间名/请求方法名
      history:this.props.history,
      payload:{
        nameValue:this.state.nameValue,
        passwordValue:this.state.passwordValue
      }
    })
    
  }
  //2、
    componentDidMount(){
    this.props.dispatch({
      type:'functionList/GetFunctionList',
      payload:{}
    })
  }
  在文件中通过this.props就可以取得
  export default connect(mapStateToProps)(FunctionList)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值