react中axios封装ajax,在react中如何封装axios

6f285365ef48317d206f79f47ca90500.png

在react中如何封装axios

一、Axios 简介

Promise based HTTP client for the browser and node.js

github:https://github.com/axios/axios

二、axios 的常用场景

1、对特定的状态码,进行特殊处理(如 4xx 状态码,统一重定向到 404 页面);

2、get 请求封装;

3、post 请求封装;

4、返回数据 json 中的特定 code,作统一处理(如后端接口定义 220 - 300的状态码,对返回文案需要统一进行弹框提示);

5、单页面的多接口的并发请求(await 导致的多余等待);

三、封装方案

预备工作

1. 能够实现全局的开始 loading、结束 loading、文案弹框的基本组件或方法(个人项目中使用了 redux 来实现全局通用组件的控制和页面缓存的使用)

2. es6 语法,并且能够支持 Promise,async,await 等语法

方法说明// proxyUtil 该对象提供一系列操作 redux 中 store 数据方法,用来做全局组件的控制

// 显示 加载中 图标

proxyUtil.startLoading()

// 关闭 加载中 图标

proxyUtil.endLoading()

// 全局文字提示弹框

proxyUtil.alertMessage(message: string)

详细代码

1、对特定请求状态码,进行特殊处理import * as axios from 'axios'

// 全局设定请求类型

axios.defaults.headers.post['Content-Type'] = 'application/json'

// 根据 axios api,对请求返回做拦截处理

axios.interceptors.response.use(function (response) {

if (response.status >= 400 && response.status < 500) {

// 对返回状态码为 4xx 的请求统一处理

// 此处统一跳转 404 页面

window.location.href = decodeURI(`${window.location.protocol}//${window.location.host}/404.html`)

} else {

return response

}

}, function (error) {

proxyUtil.alertMessage(error)

})

2、get 请求封装export function pget (url, params = {}) {

// 开始 loading

proxyUtil.startLoading()

return axios.get(url, {

params: params,

validateStatus: function (status) {

// axios 底层采用 Promise 实现,下方表达式表示只有返回 code 为 2xx 才被正常返回(resolve),非 2xx 全部当做异常(reject)

return status >= 200 && status < 300

}

}).then(response => {

// 结束 loading

proxyUtil.endLoading()

// 返回后端返回数据

return response.data

}).catch(error => {

// 异常处理

proxyUtil.endLoading()

proxyUtil.alertMessage(error)

})

}

3、post 请求封装export function ppost (url, params = {}) {

// 开始 loading

proxyUtil.startLoading()

return axios.post(url, params).then(response => {

// 结束 loading

proxyUtil.endLoading()

return response.data

}).catch(error => {

// 异常处理

proxyUtil.endLoading()

proxyUtil.alertMessage(error)

})

}

4、 返回数据 json 中的特定 code,作统一处理

这个只需要在 pget 方法或 ppost 方法中作特殊处理就行,以 pget 为例(TODO 处代码差异):export function pget (url, params = {}) {

// 开始 loading

proxyUtil.startLoading()

return axios.get(url, {

params: params,

validateStatus: function (status) {

// axios 底层采用 Promise 实现,下方表达式表示只有返回 code 为 2xx 才被正常返回(resolve),非 2xx 全部当做异常(reject)

return status >= 200 && status < 300

}

}).then(response => {

// 结束 loading

proxyUtil.endLoading()

// TODO 假定接口返回数据格式为 { code: 200, msg: "这是信息" }

// 获取接口自定义 code

let code = response.data.code

// 获取接口返回 message,也可能是一个 object,一个数组

let message = response.data.msg

// 对于接口定义的特殊范围的 code,统一对返回的 message 作弹框处理

if (code > 220 || code < 200) {

proxyUtil.alertMessage(message.toString())

}

// 返回后端返回数据

return response.data

}).catch(error => {

// 异常处理

proxyUtil.endLoading()

proxyUtil.alertMessage(error)

})

}

5、单页面的多接口的并发请求(await 导致的多余等待)export function asyncAll (requests = []) {

// 开始 loading

proxyUtil.startLoading()

// 使用 axios 的 all 方法

return axios.all(requests).then(resultArr => {

// 结束 loading

proxyUtil.endLoading()

// 对结果做特殊化处理,此处是对返回接口 code 在一定范围内作信息弹框

for (let result of resultArr) {

let code = result.code

if (code > 220 || code < 200) {

proxyUtil.alertMessage(result.msg)

}

}

// 返回每个方法返回的接口数据

return resultArr

}).catch(error => {

// 异常处理

proxyUtil.endLoading()

proxyUtil.alertMessage(error)

})

}

使用范例:

假定有两个接口请求 getUserName() 和 getUserAge(),现在一个页面需要同时请求这两个接口的数据,await 逐步等待明显浪费时间,所以我们可以采用下方写法。// 处理用户信息

async loadUserData() {

let [nameObj, ageObj] = await asyncAll([getUserName(), getUserAge()])

this.userInfo.name = nameObj.msg

this.userInfo.age = ageObj.msg

// react 此处更多是应该在得到数据处理完之后,setState({userName: nameObj.msg, userAge: ageObj.msg})

}

更多React相关技术文章,请访问React答疑栏目进行学习!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React使用Axios进行网络请求时,可以使用TypeScript进行封装以提高代码的可读性和维护性。 首先,我们可以创建一个axios实例,并对其进行一些全局配置,如设置基本的URL地址、超时时间等。可以在一个单独的文件,比如`api.ts`进行封装: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 5000 }); // 添加请求拦截器 instance.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前可以进行一些处理,比如添加token等 return config; }, (error: any) => { return Promise.reject(error); } ); // 添加响应拦截器 instance.interceptors.response.use( (response: AxiosResponse) => { // 在拿到响应数据之后可以进行一些处理,比如统一处理错误等 return response; }, (error: any) => { return Promise.reject(error); } ); export default instance; ``` 接下来,我们可以创建一个`api.ts`文件,封装各种不同的接口请求: ```typescript import axios from './axios'; export const getUserInfo = () => axios.get('/user/info'); export const updateUser = (data: any) => axios.post('/user/update', data); export const deleteUser = (userId: number) => axios.delete(`/user/${userId}`); ``` 使用时,我们只需要在组件引入对应的接口请求函数即可: ```typescript import { useEffect, useState } from 'react'; import { getUserInfo } from './api'; const UserInfo = () => { const [userInfo, setUserInfo] = useState<any>(null); useEffect(() => { getUserInfo() .then((response) => { setUserInfo(response.data); }) .catch((error) => { console.log(error); }); }, []); return ( <div> {userInfo && ( <div> <h1>User Info:</h1> <p>Name: {userInfo.name}</p> <p>Email: {userInfo.email}</p> </div> )} </div> ); }; export default UserInfo; ``` 通过封装,我们能够将网络请求和业务逻辑分离,提高代码的可维护性和可测试性。此外,使用TypeScript进行类型检查,可以在编码阶段捕获一些潜在的错误,减少运行时错误的发生。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值