我有一個小問題,我似乎無法解決。我從 Pokeapi 獲取資料以取回一些 pokemon,然后遍歷該資料以觸發另一個獲取請求以帶回與給定 pokemon 的關聯資料。
我想將此資料推送到一個陣列,以便在應用程式加載時觸發此請求并將資料保存到存盤中,因此不必發出新請求。但是...(順便說一句,我還沒有完成)
我 console.log 結果和資料在那里,但是當試圖將資料映射出來時,nada。
請在下面查看我的嘗試:
export function SomeComponent() {
let arr = [];
async function fetchPokemon() {
const pokemon = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
.then(response => response.json())
for await (const x of pokemon.results.map(async (result) => await fetch(result.url)
.then(response => response.json()))) {
arr.push(x);
}
}
fetchPokemon();
console.log(arr)
return (
<>
{arr.map((pokemon) => (
<p>
{pokemon.name}
</p>
))}
</>
)
}
我最好的猜測是控制臺正在顯示實時結果并且它們的資料實際上還沒有填充?
我想查看顯示在
標簽。
uj5u.com熱心網友回復:
在 react 中,我們應該使用 state 來存盤資料并使用 useEffect 來執行副作用操作,例如獲取資料:
export function SomeComponent() {
const [arr, setArray] = useState([]);
async function fetchPokemon() {
const pokemon = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
.then(response => response.json())
for await (const x of pokemon.results.map(async (result) => await fetch(result.url)
.then(response => response.json()))) {
setArray([...arr, x]);
}
}
useEffect(() => {fetchPokemon()}, []}
return (
<>
{arr.map((pokemon) => (
<p>
{pokemon.name}
</p>
))}
</>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447630.html
標籤:javascript 数组 反应 目的 异步
上一篇:Python-修改for回圈變數
