我有一个 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);
}
添加回答
举报
0/150
提交
取消