![](/img/trans.png)
[英]How to update an existing array of objects (add a new object to the array) with the useState hook?
[英]How to add new objects to an existing useState array using map() or foreach()?
我正在嘗試創建 Twitter 克隆,但我的新聞提要有問題。 基本上,它從我的 firebase 數據庫中為每個用戶以及當前用戶提取推文。 因此,假設您關注 Jon Abrahams 和 Terry Crews,對於這兩個中的每一個,它都會提取“tweets”集合,並且對於每條推文,它都會返回數據。
我用 useState 和 useContext 做到了這一點(因為我需要 Context 並且無法使其在 class 組件中工作,但還需要 state )。
const CurrentUser = useContext(CurrentUserContext);
const [tweets, setTweets] = useState({tweets: []});
const feedTheFeed = async (id) => {
const followedUsers = await getFollowedUsers(id);
if(followedUsers) {
followedUsers.docs.forEach(async doc => {
const followedId = doc.data();
const unformatTweets = await getTweetsByUser(followedId.follows);
if(unformatTweets.docs) {
unformatTweets.docs.map(unformatTweet => {
const tweetText = unformatTweet.data();
setTweets({
tweets: [...tweets, tweetText]
})
// console.log(tweetText);
})
}
})
// console.log(tweets);
}
}
useEffect(() => {
if(!CurrentUser) return;
if(CurrentUser.id || CurrentUser.uid) {
feedTheFeed(CurrentUser.id);
}
}, [CurrentUser]);
問題是加載組件時出現問題,它說“推文不可迭代”,但它是一個數組,所以我不明白為什么它不起作用。 有人有想法嗎?
謝謝 !
好像你想要的是
const [tweets, setTweets] = useState([]);
和
setTweets([...tweets, tweetText])
我想你想做的是這個......
常量 [tweets, setTweets] = useState([]);
setTweets(b => [...b, tweetText])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.