[英]ReactJS several fetch requests with promise
我的应用程序中需要多个获取请求才能从不同的集合中获取数据。 因此,我想使用promises来使它工作。 我从未使用过promises,尽管我对stackoverflow和其他网站进行了研究,但我还是无法使用它。
本质上,我需要两个获取请求,我想将这些请求的结果保存到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))
}
但这没效果。 我也尝试将promise放在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和图标。
我的代码在哪里出错? 我该如何解决?
您需要从方法返回Promise对象。 截至目前,你没有返回任何东西,所以它隐含undefined
。
试试这个:
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
只需添加@dfsq的答案,在返回promise之后,您可以更新每个函数中的状态:
constructor(props) {
super(props);
this.state = {
formData = {},
icons: {}
}
}
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ formData: res.json })
))
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ icons: res.json })
))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.