【发布时间】: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