如何在离线模式下更新 firebase 实时数据库 "push" 上的 UI

How to update the UI on firebase realtime database "push" in offline mode

我在我的应用程序中使用 react-native-firebase。我面临的问题是当用户在离线时尝试推送数据时如何处理 UI 更新。

如果用户在线,我们可以使用 on() 方法获取实时更新,但当他们离线时该怎么办。我们知道,推送的数据是保存在缓存中的,等用户再次上线时再推送。可以使用此缓存数据来实现我的目标吗?

这是我用来接收实时更新的代码:

var ref333 = firebase.database().ref(`/user-posts/${uid}/`)
ref333.on('value',function (snap) {
  var s = snap.val();
  console.log("NEW POSTS "+JSON.stringify(s))
})

我用来推送数据的代码。

var postData = { uid: uid, body: 'body', 标题:'title', 星数:0 };

// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
var ref222 = firebase.database().ref(`/posts/${newPostKey}`)
var ref333 = firebase.database().ref(`/user-posts/${uid}/${newPostKey}`)
ref222.push(postData, function (onComplete) {
  console.log("COMPLETED")
  ref333.push(postData,function (onComplete) {
    console.log("NEXT COMPLETED")
  }, function (error) {
    console.log("ERROR IN ",error)
  })
}, function (error) {
  console.log("error == "+error)
})

即使在离线模式下,也应该触发 .on snspashot 侦听器。 根据文档: https://firebase.google.com/docs/database/web/read-and-write

You can use the value event to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes.

这应该也适用于离线模式。如果您没有收到更新 - 还有其他问题。

通过将这行代码添加到您的本机代码中解决了这个问题:

https://rnfirebase.io/docs/v5.x.x/core/default-app#Enable-Database-Persistence