Async/await 在异步获取数据时派上用场,尤其是在
async componentDidMount() {
try {
const response = await axios.get(endpoints.one)
const data = await response
this.setState({ data, isLoading: false })
} catch (e) {
this.setState({ errors: e.response })
}
}
Run Code Online (Sandbox Code Playgroud)
此外,当从多个端点获取时,可以轻松地使用
Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]).then(([data1, data2]) => {
console.log(data1, data2)
}).catch((err) => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
然而,如何使用aync/await 而不是Promise.all从多个源获取数据呢?
我正在使用 React Recharts 进行可视化,但是,我在显示具有不同对应对象内容的简单条形图时遇到了挑战。
[
{
"month": "2017-07",
"commodities": [
{ "name": "wheat", "moves": 100, "avg_weight": 167 },
{ "name": "maize", "moves": 150, "avg_weight": 367 },
{ "name": "grains", "moves": 89, "avg_weight": 467 }
]
},
{
"month": "2017-08",
"commodities": [
{ "name": "mangoes", "moves": 140, "avg_weight": 167 },
{ "name": "grains", "moves": 190, "avg_weight": 47 }
]
},
{
"month": "2017-09",
"commodities": [
{ "name": "wheat", "moves": 130, "avg_weight": 267 },
{ "name": "tomatoes", "moves": 176, "avg_weight": 132 }, …Run Code Online (Sandbox Code Playgroud)