我正在使用一個 API 來獲取口袋妖怪串列和看起來像這樣的相應資料。
export function SomePage() {
const [arr, setArray] = useState([]);
useEffect(() => {
fetchSomePokemon();
}, []);
function fetchSomePokemon() {
fetch('https://pokeapi.co/api/v2/pokemon?limit=5')
.then(response => response.json())
.then((pokemonList) => {
const someArray = [];
pokemonList.results.map(async (pokemon: { url: string; }) => {
someArray.push(await fetchData(pokemon))
})
setArray([...arr, someArray]);
})
}
async function fetchData(pokemon: { url: string; }) {
let url = pokemon.url
return await fetch(url).then(async res => await res.json())
}
console.log(arr);
return (
<div>
{arr[0]?.map((pokemon, index) => (
<div
key={index}
>
{pokemon.name}
</div>
))
}
</div>
);
}
代碼有效(有點)但是在第一次渲染時,即使 console.log 輸出資料,地圖也不會顯示任何內容。只有重繪 頁面后,才會顯示正確的資料。我覺得這與沒有正確處理承諾有關。也許有人可以幫助我。TIA
預期輸出:初始渲染時填充的資料(在這種情況下,將顯示口袋妖怪名稱)
uj5u.com熱心網友回復:
map本質上是同步的陣列的 in-build方法。由于fetchSomePokemon您正在其中撰寫異步代碼,因此您需要從 map 回呼函式回傳一個 Promise。
現在回傳的陣列中的專案pokemonList.results.map是承諾。你需要Promise.all使用pokemonList.results.map它await。
await Promise.all(pokemonList.results.map(async (pokemon: { url: string; }) => {
return fetchData.then(someArray.push(pokemon))
}));
uj5u.com熱心網友回復:
在您的第一次渲染中,您還沒有資料,因此arr[0]不存在供您.map使用,因此它崩潰了。您需要在映射之前檢查資料是否已經存在。
使用可選鏈接,如果沒有資料,它不會在您的第一次渲染時拋出錯誤,并且當資料到達并重新渲染時它會正確渲染。
...
return (
<div>
{arr[0]?.map((pokemon, index) => (
<div key={index}>{pokemon.name}</div>
))}
</div>
);
}
uj5u.com熱心網友回復:
在
useEffect(() => { fetchSomePokemon(); }, []);
[]告訴 react 發生這種效果沒有依賴關系,
在這里閱讀更多https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
uj5u.com熱心網友回復:
解決問題的一種方法是await在useEffect().
這是一個 POC:
export function Page() {
const [pokemon, setPokemon] = useState([]);
// will fetch the pokemon on the first render
useEffect(() => {
async function fetchPokemon() {
// ... logic that fetches the pokemon
}
fetchPokemon();
}, []);
if (!pokemon.length) {
// you can return a spinner here
return null;
}
return (
<div>
{pokemon.map(item => {
// return an element
})}
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447820.html
標籤:javascript 数组 反应 异步 承诺
上一篇:如何在ReactTS中為物件(地圖資料結構)中的每個專案呈現自定義元素?
下一篇:確認按鈕有問題。按鈕不起作用
