[英]Calling React js Fetch Calls In a Sequence
有人,请帮我一个接一个地调用这些 fetch Api,因为我正在使用存储在后端的数据来处理我的下一个请求。 我希望以这种方式依次调用它们一个完整然后下一个请求。
Promise.all([
fetch(`http://localhost:5000/zoomapi`,
requestOptions),
fetch('http://localhost:5000/getId')
.then((res) => res.json())
.then((result) => {
this.setState({ zoomid: result });
}),
fetch(`http://localhost:5000/users/zoom?name=${this.state.zoomid}`)
.then((res) => res.json())
.then((result) => {
this.setState({ zoomdata: result });
})
])
.catch((error) => {
this.setState({ error });
});
})
.setState
不是同步操作,因此不能使用const id = this.state.zoomid
,可以使用result
代替。 此外,你的承诺应该是链式的,而不是嵌套的。 例子:
fetch('http://localhost:5000/getId')
.then((res) => res.json())
.then((result) => {
this.setState({ zoomid: result });
return fetch(`http://localhost:5000/users/zoom?name=${result}`);
})
.then((res) => res.json())
.then((result) => {
this.setState({ zoomdata: result });
})
.catch((error) => {
this.setState({ error });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.