如何在 React Native 中读取 Firestore 数据?

How to read firestore data in react native?

你好,我是新手,对原生和特殊的 firebase 做出反应。我一直在看关于使用 firebase 和 react native 的教程,我阅读了 react native firebase 文档,但我被卡住了。我的 firestore 数据库中有数据,在我名为 user 的集合中,但我无法读取,无法从中获取数据。这是我的 firestore 数据库:

下面是我如何尝试在我的组件中获取数据:

const Profile = ({navigation, ...props}) => {



    async function getUserData () {
        const userCollection = await await firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).get()
        return userCollection
    }
    console.log('' + getUserData())

这个 return 我那个 : [object Object]

我也试过了,(Adrian Twarog 的 instagram 克隆教程就是这样做的):

const Profile = ({navigation, ...props}) => {

  function getUserDataFirstTry() {
        firebase.firestore()
        .collection("users")
        .doc(firebase.auth().currentUser.uid)
        .get()
        .then((snapchot) => {
            if(snapchot.exists){
                console.log('' +  snapchot.data())
            } else {
                console.log('merde ca marche pas')
            }
        })
    }

    console.log('' + getUserDataFirstTry())

但我在控制台中得到了相同的结果:[object Object]

我试图将我的函数放在 useEffect 挂钩中,但这没有任何改变。 你能告诉我我做错了什么吗? (如果可能的话,在第二个例子中,因为它是实时变化的)。谢谢。

正如 Nicholas 评论的那样,由于您将 snapchot.data() 连接到一个字符串,因此您得到了该对象的字符串表示形式,这是非常无用的。

要记录数据中的特定字段:

console.log('' +  snapchot.data().userName)

以更有用的格式记录数据中的所有字段:

console.log('' +  JSON.stringify(snapchot.data()))

注意:正确的拼写是 snapshot(不是 snapchot),但为了便于 copy/paste.

,我保留了您原来的拼写