我想看看我是否能得到一些幫助來理解我做錯了什么......我試圖映射獲取的資料并將其推送到一個名為影像的陣列中,然后在映射完成后將 setFullAdLinks 設定為影像陣列。問題是,當我呼叫 getAdLinks() 函式之后的 setCurrentImage 時,它??一直說 fullAdLinks[0].source 未定義。我嘗試過使用異步方法,但沒有成功。任何建議將不勝感激!

uj5u.com熱心網友回復:
我認為您需要Promise.all,它解決了所有 fetch 呼叫并設定狀態。
const getAdLinks = () => {
const promises = ads.map((ad) => {
return fetch(ad.image)
.then((res) => res.json())
.then((res) => {
let textLink = res[0].caption.rendered.match(regex);
let x = {
adLink: textLink[0],
source: res[0].source_url,
};
return x;
});
});
return Promise.all(promises).then(images => {
setFullAdLinks(images);
})
};
Promise.all接受Promises 陣列,因此請注意return各處的陳述句。
參考:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513972.html
上一篇:在JS中重新映射物件屬性是否昂貴?是否有基準或如何對其進行基準測驗?
下一篇:如何從JSON中獲取資訊?
