如何使用 Promise.all + Array.prototype.map() 来获取不同的数据
How to use Promise.all + Array.prototype.map() to fetch different data
我有一个 ID 数组,我正在尝试获取每个 ID 的数据,并且 return 全部作为组件状态。
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,但我找不到确切的位置和方式。
修复如下:
const fetchComments = async () => {
const response = await Promise.all(
urls.map((url) => fetch(url).then(res => res.json()))
)
const fetchedComments = [].concat.apply([], response);
setComments(fetchedComments);
}
我有一个 ID 数组,我正在尝试获取每个 ID 的数据,并且 return 全部作为组件状态。
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,但我找不到确切的位置和方式。
修复如下:
const fetchComments = async () => {
const response = await Promise.all(
urls.map((url) => fetch(url).then(res => res.json()))
)
const fetchedComments = [].concat.apply([], response);
setComments(fetchedComments);
}