gpt4 book ai didi

javascript - 在 React 中使用 setState 进行多个获取请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:23 25 4
gpt4 key购买 nike

我正在编写一个组件,该组件将向站点的两个不同路径发出提取请求,然后将其状态设置为生成的响应数据。我的代码看起来像这样:

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 仍然是 Promises,还没有成为真正的 JSON 对象。无论哪种方式,我都无法弄清楚这里发生了什么。任何帮助或解释将不胜感激

最佳答案

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 数组包装到 Promise.all 以使其成为 Promise 类型

关于javascript - 在 React 中使用 setState 进行多个获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49754270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com