代码之家  ›  专栏  ›  技术社区  ›  William

使用添加在react componentdidmount中的子级访问firebase数据

  •  1
  • William  · 技术社区  · 6 年前

    我正在试验FireBase,我以前写过类似下面的代码,但出于某种原因,我没有得到我所期望的。

    当下面的react组件安装时,我希望 this.state.clients 要用查询的FireBase数据填充的数组。问题是当组件加载时 this.state.客户 为空(没有错误)。我还提供了我的模式的快照图像。我使用的是“reatime数据库”,而不是更新的“cloud firestore”。

    谢谢您!

    enter image description here

    代码

    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
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Josh Pittman    6 年前

    它是空数组,因为您在构造函数中声明它为空数组。“child added”事件尚未激发。如果您转到FireBase控制台并手动将项目添加到“客户端”,那么这将触发“子添加”事件,并且该事件将显示在您的UI中。如果希望所有现有事件的值为onload,请将'child_added'替换为'value'。

        2
  •  -1
  •   William    6 年前

    我忘了在“规则”选项卡中设置读取权限