React取消请求操作
axios取消请求
axios中取消请求有两种方式:
- 第一种就是设置超时时间自动取消请求。
- 第二点就是我们自己趋势线手动的取消请求
axios手动取消请求
简单封装axios拦截器
我们书写的是react中axios手动取消请求,自然就需要去封装一个axios。 我在这的操作就是直接取用的官网的axios拦截器。我们看到有一个请求拦截器和一个响应拦截器,我们接下来是在请求拦截器中进行操作。
import axios from 'axios'
const http = axios.create()
// 添加请求拦截器
http.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error)
}
)
// 添加响应拦截器
http.interceptors.response.use(
function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
const { data } = response
return data
},
function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error)
}
)
AbortController
从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController :
取消请求
//取消请求
let httplist = []
const removeHttp = config => {
let index = httplist.findIndex(v => v.url === config.url && v.method === config.method)
if (index >= 0) {
//取消请求
httplist[index].controller.abort()
//删除当前数据
httplist.splice(index, 1)
}
}
http.interceptors.request.use(
function (config) {
removeHttp(config)
//取消操作
//在push之前遍历数组找到相同的请求取消掉
const controller = new AbortController()
config.signal = controller.signal //用来取消操作的key
config.controller = controller //将控制器绑定到每个请求身上
httplist.push({ ...config }) //每次的请求加入到数组
return config
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error)
}
)