如何使用 Promise.all + Array.prototype.map() 获取不同的数据

我有一个 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,但我找不到具体位置和方式。


萧十郎
浏览 119回答 1
1回答

猛跑小猪

这是修复方法:const fetchComments = async () => {&nbsp; &nbsp; const response = await Promise.all(&nbsp; &nbsp; &nbsp; urls.map((url) => fetch(url).then(res => res.json()))&nbsp; &nbsp; )&nbsp; &nbsp; const fetchedComments = [].concat.apply([], response);&nbsp; &nbsp; setComments(fetchedComments);&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript