第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

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

1 回答

?
猛跑小豬

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊

這是修復(fù)方法:


const fetchComments = async () => {

    const response = await Promise.all(

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

    )

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

    setComments(fetchedComments);

  }


查看完整回答
反對(duì) 回復(fù) 2023-10-14
  • 1 回答
  • 0 關(guān)注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)