我使用axios
来解决 ajax 请求的axios
问题,因为reactJS
+flux
在渲染 UI 中,这个时间线已经开始了。在我的应用程序中,有第三个时间线(reactJS 组件)。应用程序在任何滚动事件后发送 ajax 请求以获取实际数据。在服务器上处理请求可能比下一个滚动事件更
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
如何在axios
中取消 / 中止请求?
Axios 目前不支持取消请求,详情请参见this issue。
更新:在 axios v0.15 中添加了Cancellation support。
编辑:axios 取消令牌 API 基于撤回的可取消承诺建议。
更新 2022:从 v0.22.0Axios supports AbortController开始以获取 API 的方式取消请求:
例子:
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
使用 useEffect 钩子:
useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
console.log(response.data)
setPost(response.data)
setIsLoading(false)
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => {
ourRequest.cancel() // <-- 3rd step
}
}, [])
注意:对于 POST 请求,将 cancelToken 作为第三个参数传递
Axios.post(`endpointURL`, {data}, {
cancelToken: ourRequest.token, // 2nd step
})
通常你想取消 previous Ajax 请求,并忽略它即将到来的响应,只有当该实例的一个新的 Ajax 请求启动时,为此,请执行以下操作:
示例:从 API 获取一些注释:
// declare an ajax request's cancelToken (globally)
let ajaxRequest = null;
function getComments() {
// cancel previous ajax if exists
if (ajaxRequest ) {
ajaxRequest.cancel();
}
// creates a new token for upcomming ajax (overwrite the previous one)
ajaxRequest = axios.CancelToken.source();
return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
console.log(response.data)
}).catch(function(err) {
if (axios.isCancel(err)) {
console.log('Previous request canceled, new request is send', err.message);
} else {
// handle error
}
});
}
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
class Abc extends Component {
componentDidMount() {
this.Api();
}
Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default Abc;
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(60条)