首页 文章

如何引用firebase的孩子?

提问于
浏览
0

问题

我正在尝试从我正在制作的基本社交媒体应用中的帖子中获取评论列表 . 我在一篇文章中推了几条评论,并试图通过原帖的密钥将它们作为列表检索 . 我正在使用此代码,我没有得到任何东西:

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是帖子的关键,我试图 grab 评论 .

Firebase Layout

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

1 回答

  • 1

    您无法将回调传递到 one() and 实现 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);
        });
    }
    

相关问题