【问题标题】:Why is my data coming back in a random order, how do I make it right?为什么我的数据以随机顺序返回,我该如何正确处理?
【发布时间】:2020-02-11 12:06:06
【问题描述】:

我正在使用 PokeAPI 在 React 中制作 pokedex。这个想法是让它们像口袋妖怪卡一样。一切正常,但数据并不总是以正确的顺序返回(即有时说喷火龙卡片的背面,前面有大鳞龙的地图)。它不应该总是正确映射吗,因为第二次调用是在一个承诺中?

class Cardcontainer extends Component {
state= {
    pokemon: [],
    cardBack: []
}

componentDidMount() {
       fetch('https://pokeapi.co/api/v2/pokemon')
       .then(res => res.json())
       .then(res=> {
        this.setState({
            pokemon: [...res.results]
        })
       })
       .then(res=> {
           this.state.pokemon.forEach((poke)=> {
               fetch(poke.url)
               .then(res => res.json())
               .then(res => {
                   this.setState({
                       cardBack: [...this.state.cardBack, 
res]
                   })
               })
           })
       })

}

【问题讨论】:

  • .forEach() 立即启动所有fetch(poke.url) 调用并并行运行它们。他们完成的订单是不确定的,取决于他们要去的服务器。您可以使用Promise.all(this.state.pokemon.map(poke => {return fetch(...).then(res => res.json())})).then(results => { process all the results here in order}) 之类的东西按顺序处理它们。
  • 添加返回到this.setState() 以确保回调链将按顺序处理。
  • @boosted_duck 在 setState 中返回会引发错误。 jfriend回答有效。

标签: javascript reactjs asynchronous promise


【解决方案1】:

假设您要求的是按照您发出fetch() 调用的顺序调用this.setState({cardBack: ...}),那么您可以通过收集所有fetch() 结果来实现Promise.all() .这将并行运行它们,但按顺序收集所有结果。然后,当它们都完成后,您可以按照您发出 fetch() 请求的顺序对每个结果调用 this.setState()

class Cardcontainer extends Component {
state= {
    pokemon: [],
    cardBack: []
}

componentDidMount() {
   fetch('https://pokeapi.co/api/v2/pokemon')
   .then(res => res.json())
   .then(res=> {
        this.setState({pokemon: [...res.results]});
        return Promise.all(this.state.pokemon.map(poke=> {
           return fetch(poke.url).then(res => res.json())
        }));
   }).then(results => {
       // process all the results in order
       results.forEach(res => {
           this.setState({
               cardBack: [...this.state.cardBack, res]
           })
       })
   });
}

如果这不是您所要求的,那么请编辑您的问题以使请求更清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多