亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Promise.all + Array.prototype.map() 獲取不同的數據

如何使用 Promise.all + Array.prototype.map() 獲取不同的數據

蕭十郎 2023-10-14 16:47:57
我有一個 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,但我找不到具體位置和方式。
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

這是修復方法:


const fetchComments = async () => {

    const response = await Promise.all(

      urls.map((url) => fetch(url).then(res => res.json()))

    )

    const fetchedComments = [].concat.apply([], response);

    setComments(fetchedComments);

  }


查看完整回答
反對 回復 2023-10-14
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號