【发布时间】:2019-01-03 16:09:21
【问题描述】:
我正在尝试使用 Firebase,并且我之前编写过类似以下的代码,但由于某种原因,我没有得到我期望的结果。
当下面的 React 组件挂载时,我希望 this.state.clients 数组将填充查询的 firebase 数据。问题是当组件加载时this.state.clients 是空的(并且没有错误)。我还包括了我的架构的快照图像。我使用的是“实时数据库”,而不是较新的“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
【问题讨论】:
-
你的
child_added回调被调用了吗? -
看起来不像,但我不知道为什么。我认为这是您获取 componentDidMount 上所有相应数据的方式
-
您的客户是否有权读取数据?检查您的日志输出以获取相关错误消息,特别是“权限被拒绝”。
-
不,没有错误。当我在 componentDidMount 中 console.log this.clientsRef 它返回对象。是的,客户有权限。
-
嗯...在那种情况下,我看不出出了什么问题。希望其他人发现问题。
标签: javascript reactjs firebase firebase-realtime-database