Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应firebase数组长度0_Reactjs_Firebase_Firebase Realtime Database - Fatal编程技术网

Reactjs 反应firebase数组长度0

Reactjs 反应firebase数组长度0,reactjs,firebase,firebase-realtime-database,Reactjs,Firebase,Firebase Realtime Database,我在firebase和setState中获取了数据, 此.state.data数组的戳记为0 我不知道为什么,我需要你的帮助 constructor() { super(); this.state = { data:[], } } componentDidMount(){ this.getData(); } getData(){ const arrayItem = []; firebase.database().ref('da

我在firebase和setState中获取了数据, 此.state.data数组的戳记为0

我不知道为什么,我需要你的帮助

constructor() {
    super();
    this.state = {
        data:[],
    }
}


componentDidMount(){
    this.getData();
}

getData(){
    const arrayItem = [];
    firebase.database().ref('data').on('value', (snapshot) =>{
        snapshot.forEach(function(childSnap){
            arrayItem.push({
                key:childSnap.key,
                data:childSnap.val()
            })
        })
    })
    this.setState({
        data:arrayItem
    })
}

render() {
    {console.log(this.state.data)}

firebase逻辑是异步的,因此您必须在
回调上的
内部使用
setState
,否则
arrayItem
数组将为空

示例

getData() {
  firebase
    .database()
    .ref("data")
    .on("value", snapshot => {
      const data = [];

      snapshot.forEach(function(childSnap) {
        data.push({
          key: childSnap.key,
          data: childSnap.val()
        });
      });

      this.setState({ data });
    });
}