首页 > 解决方案 > 使用useEffect在react-native中获取Firebase错误

问题描述

从 Firestore 中的文档获取数据以响应本机时出现错误

我使用 useEffect 来执行此操作,并且只运行一次。问题是,我第一次运行查询时它返回 Empty(我设置了一个控制台日志来检查这个)。但是,如果我从 useEffect 中删除 [] 并让它无限运行,则在第二次运行时它会获取数据。

这可能是firebase问题还是我的代码?这怎么能解决?我应该尝试运行 useEffect 2 次吗?这是怎么做的?

useEffect(() => {
    
firebase.firestore()
.collection("allPosts")
.where(firebase.firestore.FieldPath.documentId(), '==', props.route.params.postId)
.get()
.then((snapshot) => {
    let data = snapshot.docs.map(doc => {
        const data = doc.data();
        const id = doc.id;
        return { id, ...data }
    })
    setPost(data)
})

 if (post[0]?.field) {
     console.log(post[0].field)
 } else {
     console.log('Empty')

    
 }
}, [])

标签: reactjsfirebasereact-nativeuse-effect

解决方案


您应该在对 firestore 查询的检查中使用键而不是 firestore 字段值。

喜欢 :

const postId = props?.route?.params?.postId

useEffect(() => {
    firebase.firestore()
        .collection("allPosts")
        .where('id', '==', postId)
        .get()
        .then((snapshot) => {
            let data = snapshot.docs.map(doc => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data }
            })
            setPost(data)
        })
}, [postId])
  • 确保密钥名称存在于 firestore 文档中。

推荐阅读