【问题标题】:How to use firebase in DrawerNavigator and sync retrieve data如何在 DrawerNavigator 中使用 firebase 并同步检索数据
【发布时间】:2020-02-12 20:38:02
【问题描述】:

目标

我想从 firebase 中检索用户 name,然后在 Text 组件中使用,但它在从 firebase 加载数据之前返回,这导致文本得到未定义

抽屉代码:

export default Slidebar = (props) => {
  var name;

  firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/profile').once("value")
  .then( (snapshot) => {
    name = (snapshot.val().name)
    console.log('snapshot name:', name)
  }) 

  return(
    <ScrollView style={{backgroundColor: "#121212"}}>
      <ImageBackground source={{uri: 'https://www.redebrasilatual.com.br/wp-content/uploads/2019/05/maconha-projeto.jpg'}} 
        style={{ padding: 16, paddingTop: 48 }} 
      >
        <Text style={styles.name}> { name, console.log('text name: ', name) } </Text>        
        <Text style={styles.email}>email@example.com</Text>


        <TouchableOpacity style={{height: 40, width: 40}} onPress={() => console.log(name)} >
          <View style={{flex: 1, backgroundColor: 'white'}} />
        </TouchableOpacity>

      </ImageBackground>

      <View style={styles.container}>
          <DrawerNavigatorItems {...props} />
      </View>
    </ScrollView>
  )
}

控制台输出:

INFO 17:06 text name: undefined INFO 17:06 snapshot name: Joao Pedro

【问题讨论】:

    标签: firebase react-native firebase-realtime-database react-navigation-drawer


    【解决方案1】:

    解决了! 我之前已经尝试过useState,但我认为我做错了什么,但现在它运行良好!

    const [name, setName] = useState("teste");
      const [email, setEmail] = useState("email");
    
      firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/profile').once("value")
      .then( (snapshot) => {
        setName(snapshot.val().name)
        setEmail(snapshot.val().email)
      }) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多