我正在一个React应用程序中使用API,并尝试将API调用作为一个承诺返回。我使用的Promise.all()方法非常有效。但是,我卡在了尝试使用forEach()或map()来遍历两组数据并将它们保存到状态中以及它们自己的名称。承诺代码正常工作,我确定有一个简单的解决方案,但我已经为此苦苦思索很长时间了!我尝试搜索所有.map和.forEach文档,但没有找到相关内容!
API调用返回两个不同的数组。我需要将这两个数组分别设置为State,并赋予它们各自的名称。这是否可行?
fetchData(){
this.setState({loading: true})
const urls = ['https://api.spacexdata.com/v3/launches/past', 'https://api.spacexdata.com/v3/launches']
let requests = urls.map(url => fetch(url));
Promise.all(requests)
.then(responses => {
return responses
})
.then(responses => Promise.all(responses.map(r => r.json())))
.then(launches => launches.forEach(obj => {
// I need to set both values to state here
}))
.then(() => this.setState({loading: false}))
}
API调用返回两个不同的数组。我需要将这两个数组分别设置为State,并赋予它们各自的名称。这是否可行?