React的axios的模块封装以及处理Loading
1.安装yarn add axios 或者 npm install axios
2.在目录下创建axios目录,在目录下创建一个instance.js文件,该文件是你封装模块化的文件夹,用于封装axios的方法以及暴露接口。
3.引入axios
import axios from 'axios'
//这个是redux的store用于存放全局的Loading的值引入请安装自己的路径引入
import store from '../../store/index'
4.创建axios实例以便于全局配置axios的配置
var $http=axios.create({
//超时时间 根据自己所需配置
timeout:5000
})
5.使用axios的响应器与拦截器
//拦截器
$http.interceptors.request.use(function (config) {
//你可以在去请求前做的一些时候
//比如向请求头添加token以及处理全局loading但是每次调用api时都会进行loading所以我们使用按需引入loading
return config;
}, function (error) {
return Promise.reject(error);
});
//响应器
$http.interceptors.response.use(function (response) {
// 响应器你可以在这里进行数据进行响应之后处理的一些抒情
loadinger(false) //这个函数是用来处理loading的
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
6.接下来我们创建处理loading的函数创建loading函数
function loadinger(flag){
// 通过dispatch发送不同的action来执行不同的reducer
if(flag===true){
store.dispatch({
type:"GALOB_DATA",
})
}else{
store.dispatch({
type:"GLOAD_FLASE",
})
}
}
7.看看redux的reducer的值得判断
import { handleActions } from 'redux-actions'
这里我使用了redxu-actions中间件简化了reducer
const defaultState={
data:""
}
const reducers=handleActions{
//使loading显示
GALOB_DATA:(state)=>({...state,data:true}),
//使loading隐藏
GLOAD_FLASE:(state)=>({...state,data:false})
},defaultState)
export default reducers;
8.创建一个http类通过在类里创建静态方法来进行axios的封装
// 这里我使用了Es7的async/await
class http{
//get
static async get(url,params,loading){ //loading为你要按需使用的loading的值如果为true就开启如果为false就不开启
//因为await使异步等待执行所以他会先执行loading函数
loading?loadinger(loading):loadinger(undefined)
return await $http.get(url,{params})
}
//post
static async post(url,params,loading){
loadinger(loading)
return await $http.post(url,{params})
}
//all
static async all(arr){
//判断传入的值是不是数组如果不是的话就抛出‘错误参数’的弹窗
if(Object.prototype.toString.call(arr)==="[object Array]"){
return await axios.all(arr) //注意这里的不是实例上的方法是axios的方法
}else{
const error =new Error("错误参数")
try{
throw error
}catch(error){
alert(error)
}
}
}
}
export default http;
9.调用模块
react组件使用
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { createAction } from 'redux-actions'
import http from '../component/axios/instance'
class Ceshi extends Component {
constructor(props) {
super(props);
this.state = { };
}
componentDidMount(){
const API="https://5b5e71c98e9f160014b88cc9.mockapi.io/api/v1/lists"
http.get(API,{},true) //true动态开启loading值
.then(function(data){
console.log(data)
})
}
render() {
const {list,dispatch } = this.props
return (
<>
// 这里就先使用标签代替loading吧 哈哈哈
//通过判断redux里面的值来动态改变loading
{list.reducer1.data?<div>loading...</div>:<div>over</div>}
</>
);
}
}
const mapStateToProps=(state)=>{
return{
//将redux的值影射到props中
list:state
}
}
export default connect(mapStateToProps)(Ceshi);
OK,到这里就基本介绍完了,第一个写博客,请大家多多提意见。