【问题标题】:React Native fetching data from Firebase does not workReact Native 从 Firebase 获取数据不起作用
【发布时间】:2021-08-17 14:48:00
【问题描述】:

我有一个主屏幕,用于从 Firebase 制作的集合中加载提要。 firebase 配置适用于网络,它位于另一个文件中,并且工作正常。奇怪的是,当我删除方法调用时,它可以工作,但是当我刷新主屏幕时是空白的。此外,firestore 工作正常,post 和 cmets 上传成功。可能是什么问题?

  const HomeScreen = () => {
    
  const [posts, setPosts] = useState(null);
  const [loading, setLoading] = useState(true);

    
  const fetchPosts = async() => {
    try {
      const list = [];
      await firebase.firestore();
      db.collection('posts')
      .get()
      .then((querySnapshot) => {
          querySnapshot.forEach((doc) => {
            const {userId, post, postImg, postTime, likes, comments} = doc.data();
            list.push({
            id: doc.id,
            userId,
            userName: 'Test name',
            userImg: require('../assets/users/user-7.jpg'),
            postTime: postTime,
            post,
            postImg,
            liked: false,
            likes,
            comments,
          })
          })
      })

      setPosts(list);

      if(loading) {
        setLoading(false);
      }

      console.log('Posts', list);
    } catch(e) {
      console.log(e);
    }
  }
  useEffect(() => {
    fetchPosts();
  }, [])
   
    

    return (
        <Container>
            <FlatList
                data={posts}
                renderItem={({item}) => <PostCard item={item} />}
                keyExtractor={(item) => item.id}
                showsVerticalScrollIndicator={false}
            />
        </Container>
    );
}

【问题讨论】:

    标签: firebase react-native google-cloud-firestore


    【解决方案1】:

    setPosts 将在您的承诺解决之前运行。你的函数是async 那么为什么不使用await 而不是promise 链,如图所示:

    const fetchPosts = async () => {
      try {
        const list = [];
        const db = firebase.firestore()
      
        const querySnapshot = await db.collection('posts').get()
        querySnapshot.docs.forEach((doc) => {
          const {userId, post, postImg, postTime, likes, comments} = doc.data();
          list.push({
            id: doc.id,
            userId,
            userName: 'Test name',
            userImg: require('../assets/users/user-7.jpg'),
            postTime: postTime,
            post,
            postImg,
            liked: false,
            likes,
            comments,
          })
        })
    
        setPosts(list);
    
        if(loading) {
          setLoading(false);
        }
      } catch (e) {
        console.log(e)
      }
    }
    

    【讨论】:

    • 我觉得应该是querySnapshot.docs.forEach
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2018-11-07
    • 2021-11-13
    相关资源
    最近更新 更多