我有一个 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,但我找不到具体位置和方式。
猛跑小猪
相关分类