Demand scenarios
HTTP is slow to respond when users click buy or perform other operations
Before receiving feedback, the request and response on the current page are interrupted when the user clicks Back or switches to another page
instantiationCancelToken
The home page needs to instantiate a CancelToken
import axios from "axios";
const CancelToken = axios.CancelToken;
Copy the code
The initiating
It is then called when a request is made
Create a variable such as cancel to store the cancellation method of the request
let cancel;
axios.get('/testApi', {
cancelToken: new CancelToken(functionexecutor(c) { cancel = c; })});Copy the code
callCancelToken
Call this variable whenever you need to cancel
It is recommended to do a type check and then recharge to the initial value to ensure that AXIos has instantiated a CancelToken
if (typeof cancel===`function`){
cancel()
cancel=null
}
Copy the code
To viewhttp
state
In the Chrome control panel, you can see the status of the request to cancel
Reference documentation
Axios documentation address: www.axios-js.com/docs/