Multiple fetch requests with setState in React(在 React 中使用 setState 的多个获取请求)
问题描述
我正在编写一个组件,它将向站点的两个不同路径发出获取请求,然后将其状态设置为生成的响应数据.我的代码如下所示:
I'm writing a component that will make fetch requests to two different paths of a site, then set its states to the resulting response data. My code looks something like this:
export default class TestBeta extends React.Component {
constructor(props){
super(props);
this.state = {
recentInfo: [],
allTimeInfo: []
};
}
componentDidMount(){
Promise.all([
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent'),
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
])
.then(([res1, res2]) => [res1.json(), res2.json()])
.then(([data1, data2]) => this.setState({
recentInfo: data1,
alltimeInfo: data2
}));
}
但是,当我去渲染我的两个状态时,我发现它们实际上仍然是空的,实际上并没有被设置为任何东西.我觉得我可能错误地使用了 Promises 或 fetch() API,或者误解了 setState 的工作原理,或者是两者兼而有之.我测试了一下,发现在第一个 then() 之后,我的 data1 和 data2 出于某种原因仍然是 Promise,还没有成为真正的 JSON 对象.无论哪种方式,我都无法弄清楚这里发生了什么.任何帮助或解释将不胜感激
However, when I go to render my two states, I find that they are actually still empty, and in fact have not been set to anything. I feel like I might be using either the Promises or fetch() API wrong, or misunderstanding how setState works, or a combination of things. I tested around and found that after the first then(), my data1 and data2 were still Promises for some reason, and had not become actual JSON objects yet. Either way, I cannot figure out for the life of me what's going on here. Any help or explanation would be appreciated
推荐答案
export default class TestBeta extends React.Component {
constructor(props){
super(props);
this.state = {
recentInfo: [],
allTimeInfo: []
};
}
componentDidMount(){
Promise.all([
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent'),
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
])
.then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
.then(([data1, data2]) => this.setState({
recentInfo: data1,
alltimeInfo: data2
}));
}
如果您在 then
处理程序中返回 Promise,则它被解析为值.如果您返回任何其他内容(例如示例中的 Array),它将按原样传递.因此,您需要将您的承诺数组包装到 Promise.all
以使其成为 Promise 类型
If you return Promise in then
handler, then it's resolved to value. If you return anything else (like Array in your example), it will be passed as is. So you need to wrap your array of promises to Promise.all
to make it Promise type
这篇关于在 React 中使用 setState 的多个获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 React 中使用 setState 的多个获取请求


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01