简体   繁体   English

React Native w/ firebase “未定义不是对象”

[英]React Native w/ firebase “undefined is not an object”

Getting this error:收到此错误:

TypeError: undefined is not an object (evaluating 'doc.data().books')

from this code:从此代码:

    const getData = () => {
        const snapshot = db.collection('users').doc(userEmail).onSnapshot((doc) => {
            setData(doc.data().books)
        })

    }

    useEffect(() => {
        getData()
    }, [])
 

this is the firestore database, trying to get to the updated boo collection (gets shown in a flatlist that needs to get updated when new content is added to the collection) Note that there's a users collection that is offscreen.这是 firestore 数据库,试图访问更新的 boo 集合(显示在平面列表中,当新内容添加到集合时需要更新)请注意,屏幕外有一个 users 集合。

在此处输入图像描述 I'm pretty sure it's something that I'm doing wrong on my snapshot but I'm really not sure what, all help is greatly appreciated:)我很确定这是我在快照上做错了,但我真的不确定是什么,非常感谢所有帮助:)

The error is telling you that doc.data() returned undefined, which means the document you requested doesn't exist.该错误告诉您doc.data()返回未定义,这意味着您请求的文档不存在。 You probably passed a value for userEmail other than what you expected it to be.您可能为userEmail传递了一个与您预期不同的值。 Since you didn't show the value, we don't know for sure what went wrong.由于您没有显示价值,我们不确定出了什么问题。

I will point out that document IDs must be exact matches, so if the email address wasn't exactly "Email@email.com" with a capital E, the query will not return a document using what you've shown here.我将指出文档 ID 必须完全匹配,因此如果 email 地址不完全是带有大写 E 的“Email@email.com”,则查询将不会使用您在此处显示的内容返回文档。

There are several possibilities.有几种可能性。 However, db is not defined within the scope of the getData function... where is it defined?但是,db 没有在 getData function 的 scope 中定义......它在哪里定义?

If I correctly understand your question, you want to get the documents in the books (or boo ?) subcollection of the user document with id corresponding to userEmail .如果我正确理解您的问题,您想获取用户文档的books (或boo ?)子集合中的文档,其 id 对应于userEmail

If this assumption is correct, you should do as follows:如果这个假设是正确的,您应该执行以下操作:

const getData = () => {
    db.collection('users').doc(userEmail).collection('books')
       .onSnapshot(querySnapshot => {
           var books = [];
           querySnapshot.forEach(doc => {
               books.push(doc.data());
           });
           // Here you have an array of all the book objects.
           // It's up to you to use it as you wish with your setData() function
       });

}

Note that with doc.data().books you are actually trying to get the books field of the user doc.请注意,使用doc.data().books您实际上是在尝试获取用户文档的books字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM