我正在试验FireBase,我以前写过类似下面的代码,但出于某种原因,我没有得到我所期望的。
当下面的react组件安装时,我希望
this.state.clients
要用查询的FireBase数据填充的数组。问题是当组件加载时
this.state.客户
为空(没有错误)。我还提供了我的模式的快照图像。我使用的是“reatime数据库”,而不是更新的“cloud firestore”。
谢谢您!
代码
import React, {Component} from 'react';
import firebase from 'firebase/app';
class Dashboard extends Component{
constructor(props){
super(props)
this.state = {
clients: []
}
this.clientsRef = firebase.database().ref('clients')
}
componentDidMount(){
this.clientsRef.on('child_added', snapshot => {
const client = snapshot.val();
client.key = snapshot.key;
this.setState({ clients: this.state.clients.concat( client ) })
});
}
render(){
console.log(this.state.clients); // <---- is an empty array after component mounts but *should* contain data per the above firebase query
return(
<div>
<h2>All Clients </h2>
</div>
)
}
}
export default Dashboard