我有一個 ID 數組,我試圖用每個 ID 獲取數據并將其全部作為組件狀態返回。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);}當我只獲取一個 ID 時,它工作正常: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 的第一種情況并非如此。有時,當我更改代碼并且不重新加載頁面時,Promise.all 會執行 console.log,但它仍然沒有呈現在頁面上:<div> {comments.map(comment => ( <p key={comment}>{comment.text}</p> ))}</div>在第二種情況下,只有一個 ID,console.log 和渲染工作都完美,所以我可能搞砸了 Promise.all,但我找不到具體位置和方式。
如何使用 Promise.all + Array.prototype.map() 獲取不同的數據
蕭十郎
2023-10-14 16:47:57