Firebase引用没有任何结果

时间:2017-12-05 16:42:01

标签: javascript firebase react-native firebase-realtime-database

问题

我正在尝试从我的firevase服务器检索数据,而我用来执行此操作的参考代码不会检索任何内容。

getItems(){

var items = [];

var query = firebase.database()。ref('users')。child(expoID).orderByKey();

query.once('value',(snap)=> {

var items = [];

snap.forEach((child)=> {

items.push({

内容:child.val()。content,

postKey:child.val()。okey,

color:child.val()。color,

notifKey:child.key

});

});

items.reverse();

})。then(()=> {

this.setState({firebaseItems:items});

});

}

expoID是一个预定义的变量,用expo的常量定义。

服务器

firebase server 用户下的第一项是上面代码中看到的expoID。我测试过,它的ID相同。

1 个答案:

答案 0 :(得分:0)

orderByKey仅创建Query。 要检索您需要监听事件的实际数据。 onceon是您的朋友。有以下事件类型:"值"," child_added"," child_changed"," child_removed"和" child_moved。"

获取数据使用"值"。因此,例如,获取数据的代码是:

ref('users').child(expoID).orderByKey().once('value').then(function(snapshot) {
   console.log(snapshot.val());
});

希望这有帮助!

修改

// Notice I removed the first declaration of var items
// var items = [];

var query = firebase.database().ref('users').child(expoID).orderByKey();

query.once('value', (snap) => {

  // This array is ONLY valid inside this callback
  var items = [];

  snap.forEach((child) => {
    items.push({
      content: child.val().content,
      postKey: child.val().okey,
      color: child.val().color,
      notifKey: child.key
    });
  });
  items.reverse();
  this.setState({ firebaseItems: items });
});
// No need to set your state in the promise. Just do it directly inside the callback