简体   繁体   English

使用React componentDidMount中的child_add通过键访问Firebase数据

[英]Access firebase data by key using child_added in React componentDidMount

I'm experimenting with Firebase and I've written code like the following before but for some reason I am not getting what I expect. 我正在尝试使用Firebase,并且之前已经编写了以下代码,但是由于某种原因,我没有达到我的期望。

When the React component below mounts I expect the this.state.clients array to be populated with the queried firebase data. 当下面的React组件挂载时,我希望this.state.clients数组中填充有查询到的this.state.clients数据。 The problem is that when the component loads this.state.clients is empty (and there are no errors). 问题在于,当组件加载this.state.clients为空时(并且没有错误)。 I've also included a snap shot image of my schema. 我还包括了我的架构的快照图像。 I am using the "reatime database" and not the newer "Cloud Firestore". 我正在使用“实时数据库”,而不是较新的“ Cloud Firestore”。

Thank you! 谢谢!

在此处输入图片说明

Code

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

It's an empty array because you declared it an empty array in the constructor. 这是一个空数组,因为您在构造函数中将其声明为空数组。 The 'child added' event hasn't fired yet. “添加子项”事件尚未触发。 If you go to your firebase console and manually add an item to 'clients' then this will trigger the 'child added' event and the event will show up in your UI. 如果您转到Firebase控制台并手动将项目添加到“客户端”,则这将触发“添加子项”事件,并且该事件将显示在用户界面中。 Replace 'child_added' with 'value' if you want the value of all existing events onload. 如果要加载所有现有事件的值,请将“ child_added”替换为“ value”。

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM