【发布时间】:2018-07-17 12:48:13
【问题描述】:
我的应用程序中需要多个获取请求来从不同的集合中获取数据。因此,我想使用 Promise 来实现它。 我从未使用过 Promise,尽管我对 stackoverflow 和其他网站进行了研究,但我无法让它发挥作用。
基本上,我需要两个 fetch 请求,我想将这些请求的结果保存到 2 个不同的状态。
这是我现在所拥有的:
getFormData () {
fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getData () {
return Promise.all([this.getFormData(), this.getIcons()])
}
componentDidMount () {
this.getData()
.then(([formdata, icons]) => {
console.log(form + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
但这不起作用。
我还尝试将承诺放在我的 componentDidMount() 生命周期方法中,如下所示:
componentDidMount () {
return Promise.all([this.getFormData(), this.getIcons()])
.then(([formdata, icons]) => {
console.log(formdata + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
但这并没有奏效。
我想将 /formdata 中的数据保存到具有相同名称的状态,图标也是如此,但在控制台中它只是返回 undefined undefined,而不是 formdata 和图标。
我的代码哪里出错了?我该如何解决?
【问题讨论】:
标签: javascript reactjs promise