简体   繁体   English

如何在本机反应中从firestore数据库中获取字段值

[英]How to get field value from firestore database in react native

I'm trying to get data from my firestore database into my react native project.我正在尝试从我的 firestore 数据库中获取数据到我的 react native 项目中。 I've been able to get the data of a whole collection but unsure of how I would get different field values individually.我已经能够获取整个集合的数据,但不确定如何单独获取不同的字段值。 Like how would I display the values FlagQuizscore: 83.33333333333334 WalesQuizscore:80 coins:46 from my firestore database into my react native project?就像我如何将值 FlagQuizscore: 83.33333333333334 WalesQuizscore:80 coin:46 从我的 firestore 数据库显示到我的 react native 项目中?

This code displays the values for the whole collection:此代码显示整个集合的值:

import {useEffect, useState} from "react";

export default function ModesScreen({navigation}) {
    const email = auth.currentUser.email
    const userCollectionRef = collection(db,"Users")
    const [users,setUsers] = useState([])

    useEffect(()=>{
        const getUsers = async () => {
            const data = await getDocs(userCollectionRef)
            setUsers(data.docs.map((doc)=>({...doc.data(), id: doc.id})))
        }
        getUsers()
    },[])

    return (
        <View style={styles.container}>
            {users.map((users)=>{return<View key={doc.id}>
                <Text>{users.WalesQuizscore}</Text>
                <Text>{users.coins}</Text>
            </View>})}
        </View>
    );
}

Results from my database I want to get into my react native project:我的数据库中的结果我想进入我的 react native 项目:

在此处输入图像描述

If you are just trying to get a single document then you can use getDoc() function.如果您只是想获取单个文档,则可以使用getDoc() function。 Also no need to declares users as an array.也无需将用户声明为数组。 Try refactoring the code as shown below:尝试重构代码,如下所示:


import {useEffect, useState} from "react";

export default function ModesScreen({navigation}) {
  const email = auth.currentUser.email
  const userDocRef = doc(db,"Users", email)
  const [user, setUser] = useState({})

  useEffect(() => {
    const getUser = async () => {
      const snap = await getDoc(userDocRef)
      setUser({email, ...snap.data()})
    }
    getUser()
  },[])

  return (
    <View style={styles.container}>
      {return <View key={user.email || 'email'}>
          <Text>{user.WalesQuizscore}</Text>
          <Text>{user.coins}</Text>
        </View>})}
    </View>
  );
}

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

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