【发布时间】:2020-04-12 17:33:18
【问题描述】:
现在我正在 ReactJS 做一个更大的项目。我现在有一个页面,我需要从该页面的多个 URL (API) 获取数据。也就是说,我需要得到 40 多个这样的结果列表:城市、县、类别、性别等。这一切都在单独的 URL 中。是这样的:
https://API_URL/users
https://API_URL/country-list
https://API_URL/city
https://API_URL/gender
and etc...
我目前正在使用以下方法来获取。
componentDidMount() {
this.setState({
isLoading: true
});
axios.get(API_URL + '/country-lists', {
headers: {
Authorization: GetTokens
}
})
.then(response => response.data)
.then(
(result) => {
this.setState({
countries: result.data,
isLoading: false
});
},
(error) => {
this.setState({
error,
isLoading: false
});
}
)
}
我发现了一些额外的选项,例如 promises、axios.all()。但我想知道它们是否可以成为一个完整的解决方案。
axios.all([
axios.get(https://API_URL/users'),
axios.get(https://API_URL/country-list'
...)
])
.then(axios.spread((countries, users) => {
// ... });
和
Promise.all([users, countries, products]).then(function(values) {
...
});
您应该使用哪种方式来获取此类数据或者是否有更好的解决方案?同时,考虑到互联网连接和各种错误。
【问题讨论】: