reactjs - axios同步取数据的问题
问题描述
我正在使用 4 个 Axios.get 语句,这些语句用于一次从 4 个不同的来源获取数据。在第一次获取尝试时获取它们没有问题 - 服务正在工作并正确显示结果。据我了解,我的问题是,当我尝试使用其他 axios.get 重写结果时,它首先呈现,然后获取数据。
下面是两个 Axios.gets 的代码,其中 getCashboxBonusNDS() 在 getCashboxuserBonusNDS() 之后会导致错误。并在更改时更改 Api 服务的 switch 语句
getCashboxuserBonusNDS = (dateFrom, dateTo, client) => {
Axios.get('/api/report/sales/ndscashboxuser', {
params: { dateFrom, dateTo, client }
}).then(res => res.data)
.then((salesResultNDS) => {
this.setState({ salesResultNDS, isLoading: false });
})
.catch((err) => {
console.log(err)
})
};
getCashboxBonusNDS = (dateFrom, dateTo, client) => {
Axios.get('/api/report/sales/ndscashbox', {
params: { dateFrom, dateTo, client }
}).then(res => res.data)
.then((salesNDS) => {
const temp = _.mapValues(_.groupBy(salesNDS, 'point'), list => list.map(bs => _.omit(bs, 'point')));
const salesResultNDS = Object.keys(temp).map(key => {
return {
point: key,
cashboxesNDS: temp[key]
}
});
this.setState({ salesResultNDS, cashboxSalesResultNDS: salesNDS, isLoading: false });
})
.catch((err) => {
console.log(err)
})
};
switch (filter.value) {
case 'cashboxFiz': {
if(filterType.value==='cashbox'){
this.getCashboxBonus(dateFrom, dateTo, "fiz");
this.getCashboxBonusNDS(dateFrom, dateTo, "fiz")
}else{
this.getCashboxuserBonus(dateFrom, dateTo, "fiz");
this.getCashboxuserBonusNDS(dateFrom, dateTo, "fiz")
}
break;
}
case 'cashboxJur': {
if(filterType.value==='cashbox'){
this.getCashboxBonus(dateFrom, dateTo, "jur");
this.getCashboxBonusNDS(dateFrom, dateTo, "jur")
}else{
this.getCashboxuserBonus(dateFrom, dateTo, "jur");
this.getCashboxuserBonusNDS(dateFrom, dateTo, "jur")
}
break;
}
default:
console.log("Error: filter not detected")
}
唯一的错误信息:TypeError: Cannot read property 'reduce' of undefined
解决方案
可以将 Promise 链接在一起,以确保特定请求始终按顺序执行(同步)。我在下面提供了一个示例。
const get = (endpoint = '/', params = {}) => {
// return axios promise
return axios({
method: 'get',
url: apiHost + endpoint,
headers: { 'Authorization': 'Token ' + this.state.token },
params: params,
});
};
get('/api/some-endpoint/')
.then((response) => {
console.log(response);
//return next promise
return get('/api/another-endpoint/');
}).then((response) => {
console.log(response);
// return next promise
return get('/api/yet-endpoint');
}).then((response) => {
console.log(response);
// return next promise
return get('/api/last-endpoint/');
}).then((response) => {
console.log(response);
// finished, no more promises left in the chain
})
.catch(function (error) {
console.log('Error getting data', error);
});
推荐阅读
- php - 如何将 post_thumbnail 大小设置为特定类别或标签?
- python-3.x - 从按钮向父窗口发送信号
- flutter - 带有颤振的可重复使用的卡片小部件
- django-viewflow - Viewflow 1.6.0 中的流程和任务上的新字段是供图书馆用户使用还是仅供内部使用
- elasticsearch - 在 must bool 查询中使用 Regexp 搜索与使用 must_not bool 查询
- swift - 启动 SwiftUI 计时器
- python - 为“0”和“1”的熊猫数据框列创建“组号”列
- mysql - 如何从 Ubuntu 获取 windows phpmyadmin 数据库 (.SQL) 备份?
- c++ - 整数常量 0 导致 std::string 抛出
- c# - 尝试打开与 phpmyadmin 服务器的连接时,程序冻结