Javascript 如何在react native上从firestore检索数据

Javascript 如何在react native上从firestore检索数据,javascript,firebase,react-native,Javascript,Firebase,React Native,我试图从firestore上的集合中检索数据,但当我将此数据放入诸如Text之类的组件时,我会收到一个错误,然而,当我将相同的数据放入console.log()时,我可以毫无问题地使用其值 我的代码 const nome = firestore().collections('usuários').doc(auth().currentUser.uid).get().then( (documentSnapshot) => documentSnapshot.get('nome')) retur

我试图从firestore上的集合中检索数据,但当我将此数据放入诸如Text之类的组件时,我会收到一个错误,然而,当我将相同的数据放入console.log()时,我可以毫无问题地使用其值

我的代码

const nome = firestore().collections('usuários').doc(auth().currentUser.uid).get().then(
(documentSnapshot) => documentSnapshot.get('nome'))

return (
    <View style={{ flex: 1 }}>
                    <View style={styles.imageContainer}>
                        <Image source={require('../assets/img/user-bg.jpg')} style={styles.image} />
                    </View>


                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        <View style={styles.userLabel}>
                            <Text style={[styles.user, { color: colors.text }]}>{nome}</Text>
                            <Text style={[styles.email, { color: colors.text }]}>email</Text>
                        </View>

                        <CaretDownIcon width={8} height={8} fill={colors.text} style={{ marginRight: 10 }}/>
                    </View>
                </View>
    </View>
)
const nome=firestore().collections('usuários').doc(auth().currentUser.uid).get()。然后(
(documentSnapshot)=>documentSnapshot.get('nome'))
返回(
{nome}
电子邮件
)

要获得nome,您必须:

const nome = firestore().collections('usuários').doc(auth().currentUser.uid).get().then(
(documentSnapshot) => documentSnapshot.get('nome'))
这不会返回名称!相反:
firestore().collections('usuários').doc(auth().currentUser.uid).get()
返回一个
Promise
。因此,您希望发生的是:

  • 取名字
  • 显示名称
  • 但现在发生的是:

  • 您要求firebase使用
    .get()
    获取名称
    .get()
    。然后()
    返回一个
    承诺
    ,这是一个
    对象
    (因此会出现该错误)
  • 您的页面使用
    对象呈现
  • Firebase完成获取名称,然后调用
    name
    中的函数,即。
    (documentSnapshot)=>documentSnapshot.get('nome')
  • 因此,请考虑:

  • 更改
    {nome}
    进入
    {this.state.nome}
  • (documentSnapshot)=>documentSnapshot.get('nome')
    更改为
    (documentSnapshot)=>{let _nome=documentSnapshot.get('nome');this.setState({nome:_nome})
  • 然后会发生什么呢

  • 您要求firebase获取该名称
  • 您的页面呈现,但firebase还没有您的名字。(它将显示为未定义,但这没关系,因为:
  • Firebase获取您的姓名,然后调用
    setState
  • React在调用
    setState
    时自动用新名称更新页面
  • 如果您不想使用未定义的
    名称,可以尝试类似
    {this.state.nome | | |“等待响应…”

    如果您现在正在使用ES6函数呈现程序,则需要使用React类