如何使用map()或foreach()将新对象添加到现有useState数组中?

时间:2020-07-05 22:26:36

标签: javascript reactjs react-hooks spread-syntax

我正在尝试创建Twitter克隆,但我的新闻提要遇到了麻烦。基本上,它会从Firebase数据库中为每个用户(随后是当前用户)提取推文。因此,假设您关注Jon Abrahams和Terry Crews,对于这2个消息,它将提取“ tweets”集合,并且对于每个tweet,它将返回数据。

我使用useState和useContext进行了此操作(因为我需要Context,并且无法使其在类组件中工作,但也需要状态)。

  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]);

问题是加载组件时出现问题,它说“ tweets不可迭代”,但是它是一个数组,所以我不明白为什么它不起作用。有人有主意吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

好像你想要的是

const [tweets, setTweets] = useState([]);

setTweets([...tweets, tweetText])