我正在构建一个module.exports = {
(..)
themeConfig: {
(...),
googleAnalytics: {
trackingID: 'UA-GACODE-1',
},
(...)
应用。我的API组件包含一个我希望能够停止的异步调用。为此,我使用React Native
:。
axios.CancelToken
从组件中,我致电const source = axios.CancelToken.source();
async getProductCategoriesRequest() {
try {
let response = await catalog.get(`category`, {
cancelToken: source.token,
});
return response.data;
} catch (error) {
if (axios.isCancel(error)) {
console.log(error)
return Promise.reject();
}
}
}
上的requestCancellationHandler
:
onPress
一切正常,除非除非重新加载应用程序,否则我无法打另一个电话。我在API请求捕获中不断收到 const requestCancellationHandler = () => {
source.cancel('API request is being canceled');
props.resetState();
};
。简单的页面重新加载使我可以进行另一个异步调用
如何解决该问题而不必重新加载?
答案 0 :(得分:0)
我认为Axios docs中的第二个示例会很有用。
<script>
function showGraph()
{
var pageURL = window.location.href;
var lastURLSegment = pageURL.substr(pageURL.lastIndexOf('/') + 1);
console.log(lastURLSegment);
{
$.post("data.php?userid="+lastURLSegment,
function (data)
{
var name = [];
var marks = [];
for (var i in data) {
name.push(data[i].mydate);
marks.push(data[i].result);
}
var chartdata = {
labels: name,
datasets: [
{
label: 'Daily Profit',
backgroundColor: '#305882',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
data: marks
}
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
对于您而言,
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
和
let source;
async getProductCategoriesRequest() {
source = axios.CancelToken.source();
try {
let response = await catalog.get(`category`, {
cancelToken: source.token,
});
return response.data;
} catch (error) {
if (axios.isCancel(error)) {
console.log(error)
return Promise.reject();
}
}
}