【问题标题】:How to reference children from firebase?如何从firebase引用孩子?
【发布时间】:2017-11-25 03:34:07
【问题描述】:

问题

我正在尝试从我正在制作的基本社交媒体应用程序中的帖子中获取 cmets 列表。我将几个 cmets 推送到一个帖子中,并试图通过原始帖子的密钥将它们作为列表检索。我正在使用这段代码,但我什么也没得到:

getItems(){
var items = [];
var query = ref.child(this.state.passKey).orderByKey();
query.once ('value', (snap) => {
  snap.forEach ( (child) => {       
   items.push({
     comment: child.val().comment,
 });
 });
}).then(() => {
    this.setState({firebaseItems: items});
});
}

Ref 正在引用 firebase 上的帖子列表,而 passKey 是我试图从中获取 cmets 的帖子的关键。

Firebase 布局

posts:
    -Kzeruiwnpirnwreo:
        content: 'random post example'
        -Kzoreipwrnipgierwn:
            comment: 'comment example'
        -Kzqipeurpireroei:
            comment: 'another comment example'

【问题讨论】:

  • 您应该尝试在once() 中添加错误回调作为第三个参数——您可能会遇到权限错误或其他问题。回调中还有console.log(),这样你就可以看到什么被调用了,什么没有被调用。

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


【解决方案1】:

您不能同时将回调传递给one() 实现then()。它必须是其中之一。幸运的是,将代码修改为只使用一个非常容易:

getItems() {
    var query = ref.child(this.state.passKey).orderByKey();
    query.once('value').then((snap) => {
        var items = [];
        snap.forEach((child) => {
            items.push({
                comment: child.val().comment,
            });
        });
        this.setState({
            firebaseItems: items
        });
    }).catch((error) {
        console.error(error);
    });
}

【讨论】:

    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多