简体   繁体   English

如何在React Native中从Firebase中的数据库访问信息并显示在 <Text> ?

[英]How can I access information from a database in Firebase in React Native and display it within a <Text>?

I'm trying to read data from a realtim database in firebase but I can not get this information to be rendered in a Text component. 我正在尝试从Firebase中的realtim数据库读取数据,但是无法获取要在Text组件中呈现的信息。 I can only show the information of the object by console.log and decompose it but in the render of the screen the information is not shown. 我只能通过console.log显示对象的信息并分解它,但是在屏幕的渲染中没有显示该信息。

class UserProfileScreen extends Component<Props> {

state = {
 dataUser : []
}

componentDidMount(){
const { uid } = firebaseAuth.currentUser
this.getUserRef().child(uid).once('value',function(snapshot){
 dataUser = snapshot.val()
  console.log(dataUser.username)
 })
}

getUserRef = () => {
  return firebaseDatabase.ref('users')
}

render(){
 const {dataUser} = this.state
 return(
  <View style={styles.container}>
    <Text>{dataUser.username}</Text>
  </View>
  )
 }
}

Object obtained from the database displayed by console: 从控制台显示的数据库中获取的对象: 从控制台显示的数据库中获取的对象 ,

Android Emulator: Android模拟器: Android模拟器

What I can be doing wrong ? 我做错了什么?

You need to change the state property once the value has been retrieved: 检索到值后,您需要更改state属性:

constructor() {
  this.state = { dataUser: {} };
}

componentDidMount(){
  ...
  this.getUserRef().child(uid).once('value',function(snapshot){
    dataUser = snapshot.val()
    this.setState({
      dataUser: dataUser // es5
      dataUser // es6 
    });
  });
  ...
}

Documentation 文献资料

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

相关问题 如何从Firebase数据库读取并将信息存储在列表视图中? Android的 - How can I read from a firebase database and store the information within a list view? Android 如何获取数据库信息以文本视图显示? - How can I get my database information to display in a text view? 如何从 React-native 中的 Firebase 实时数据库中访问值? (安卓) - How to access value from Firebase Realtime Database in React-native? (android) Firebase react-native无法访问 - Firebase react-native can not access 我如何从Firebase数据库中提取三段文本并在一个textView中显示它们? - How would I pull three pieces of text from a firebase database and display them in one textView? 如何从Firebase数据库检索数据以显示标记? - How can I retrieve data from my Firebase Database to display markers? 如何使用Firebase数据库中的图像路径显示图像? - How can I display image by using image Path in Firebase database? 如何级联 ValueEventListeners 以从 firebase 实时数据库访问两个不同的节点 - How can I cascade ValueEventListeners to access to two different nodes from firebase realtime database 如何使用反应原生视频从内部存储访问我的视频? - How can I access my videos from internal storage with react native video? 我如何在 React Native webview 中从网页访问当前位置 - how can i access current location from web-page in react native webview
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM