我正在使用 PokeAPI 使用 axios 來獲取資料。
提出我的第一個請求時,口袋妖怪的訂單符合預期(1、2、3 ...)
當遍歷陣列中的每個物件以獲取更多細節(img、移動等)并將每次迭代推入陣列時,口袋妖怪順序無處不在。
例如:第一個陣列
[
0: {name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/'}
1: {name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/'}
2: {name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/'}
... ]
第二個陣列(注意這不是實際結果,因為它太長且與輸入無關)
[
0: {name: pikachu, id: 10}
1: {name: charmander, id: 3}
... ]
我想要實作的基本上是讓我的第二個陣列與同一個陣列的順序相同。
這是-edited-代碼
useEffect(() => {
setLoading(true);
let cancel;
axios.get(currentPageUrl, {
cancelToken : new axios.CancelToken(c => cancel = c)
}).then(res => {
setLoading(false);
setNextpageUrl(res.data.next);
setPreviousPageUrl(res.data.previous);
//this array is in the expected order
console.log(res.data.results)
res.data.results.forEach(async (pokemon) => {
const res = await axios.get(`${pokemon.url}`);
//this is the array I am having an issue with
setPokemons(list => [...list, res.data]);
})
return () => cancel();
})
}, [currentPageUrl]);
先感謝您
uj5u.com熱心網友回復:
由于您正在執行異步操作,因此您不能保證您將擁有相同的訂單。你最好使用Promise.all,所以你解決了所有的承諾,但它保持相同的順序。
//This array is in the expected order
console.log(results)
const pokemonPromises = results.map(pokemon => axios.get(`${pokemon.url}`))
const pokemons = await Promise.all(pokemonPromises)
setPokemons((currentArray) => [...currentArray, ...pokemons])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417915.html
標籤:
上一篇:將列與多行中的陣列合并
