如何从firebase数据库中获取最新数据?

时间:2017-12-12 04:09:09

标签: firebase firebase-realtime-database

假设我正在使用firebase数据库编写一个Twitter克隆(但更简单)。帖子仅包含邮件正文。在数据库中,除了消息体之外,我还会跟踪这些事情:

enter image description here

其中likeCount是帖子上的喜欢数量。只要有人喜欢这个帖子,它就会增加。帖子通过Cloud Functions下载,因为使用了分页,一次下载了10个帖子。所以,我的问题是,在下载时,假设每个帖子只有1个喜欢,但是如果其他人喜欢帖子,那么,现在帖子上应该有2个喜欢,我如何得到这个最新{{1无需刷新页面?

1 个答案:

答案 0 :(得分:4)

在Android中你应该这样做以获得likeCount节点的更新

FirebaseDatabase database;
String postId="KyELxNpEaRt2Y64flUn"

database.getReference().child("posts/" + postId + "/likeCount").onChildChanged(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) 
{
if (dataSnapshot.getValue() != null) {
//here you should update the value
}
})
})

在React Native中

 postRef=`/posts/${postId}/likeCount`;
 firebase.database().ref(postRef).on("child_changed", snap => {
    if (snap.val() != null) {
     //here you shold update the value
    }
  });
相关问题