我有一個(gè) ID 數(shù)組,我試圖用每個(gè) ID 獲取數(shù)據(jù)并將其全部作為組件狀態(tài)返回。let urls = commentsIds.map(id => `https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`);useEffect(() => { fetchComments();}, [])const fetchComments = async () => { let fetchedComments = []; Promise.all( urls.map(async (url) => { let response = await fetch(url) let data = await response.json(); fetchedComments.push(data); console.log(fetchedComments) }) ) setComments(fetchedComments);}當(dāng)我只獲取一個(gè) ID 時(shí),它工作正常:const fetchComments = async () => { let fetchedComments = []; const response = await fetch(`https://hacker-news.firebaseio.com/v0/item/25322480.json?print=pretty`); const data = await response.json(); fetchedComments.push(data) console.log(fetchedComments)}但 Promise.all 的第一種情況并非如此。有時(shí),當(dāng)我更改代碼并且不重新加載頁(yè)面時(shí),Promise.all 會(huì)執(zhí)行 console.log,但它仍然沒有呈現(xiàn)在頁(yè)面上:<div> {comments.map(comment => ( <p key={comment}>{comment.text}</p> ))}</div>在第二種情況下,只有一個(gè) ID,console.log 和渲染工作都完美,所以我可能搞砸了 Promise.all,但我找不到具體位置和方式。
如何使用 Promise.all + Array.prototype.map() 獲取不同的數(shù)據(jù)
蕭十郎
2023-10-14 16:47:57