[英]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模拟器:
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
});
});
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.