前端终止接口请求

1 CancelToken

1.1 创建CancelToken

import { useRef } from 'react'
import axios from 'axios'
const cancelTokenRef = useRef(null)
const CancelToken = axios.CancelToken

1.2 添加CancelToken

axios.get(url, {
	timeout: 1000 * 6, // 接口超时
	cancelToken: new CancelToken(function (c) {
		cancelTokenRef.current = c // 绑定到ref
	})
})

1.3 终止请求

// 触发handleCancel即可终止请求
const handleCancel = () => {
	if (cancelTokenRef.current) {
		cancelTokenRef.current('接口已取消~')
    	cancelTokenRef.current = null
	}
}

2 AbortController

2.1 创建AbortController

let controller = new AbortController()

2.2 添加AbortController

axios.get(url, {
	signal: controller.signal
})

2.3 终止请求

const handleCancel = () => {
	if (controller) {
		controller.abort()
		controller = null
	}
}

www.axios-http.cn

你可能感兴趣的:(前端,javascript,axios)