【发布时间】:2021-03-21 02:50:27
【问题描述】:
我想为作为 props (rootComments) 传递的数组中的每个对象获取数据并将数据添加到对象属性中:
useEffect(() => {
rootComments.map(rootComment => {
if (rootComment.kids) {
rootComment.kidsText = []
fetchKidsText(rootComment.kids)
}
})
console.log(rootComments)
rootComments.map(comment => console.log(Object.values(comment)))
}, [rootComments])
const fetchKidsText = async (ids) => {
await Promise.all(
ids.map(id => fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`).then(response => response.json()).then(result => {
rootComments.map(comment => {
if (comment.id === result.parent) {
comment.kidsText = comment.kidsText.concat(result.text)
}
})
}))
);
}
似乎它不起作用,我无法呈现 rootComments.map(comment => comment.kidsText) 并且我无法将其记录为 rootComments.map(comment => console.log(Object.values(comment)))(就像没有新的 kidsText 属性一样)或 rootComments.map(comment => console.log(comment.kidsText))(返回空大批)。
但。当我记录console.log(rootComments) 时,它返回具有新kidsText 属性的对象数组。
我的第一个想法是 useEffect() 不会等待 rootComments 在另一个组件中获取,但这似乎不是问题,所以可能是 fetchKidsText() 内部的东西或者它与 @ 交互的方式987654332@?
【问题讨论】:
-
您的代码有很多问题。我认为@kigiri 目前的回答很好地总结了这些问题。