【问题标题】:Firebase RTDB `ref.once()` being executed multiple timesFirebase RTDB `ref.once()` 被多次执行
【发布时间】:2016-07-03 10:44:18
【问题描述】:

最近在玩 firebase RTDB,我一直在使用 .once('value', v => ...) 来构建我的应用程序的 GUI。具体代码如下:

<script>
  function onAuthCompleted(usr) {
    var salesTxRef = firebaseApp.database().ref('/salesTx').limitToLast(5);
    salesTxRef.once("value", salesTx => {
      salesTx.forEach(txRef => {
        const tx = txRef.val();
        const $item = $('<li></li>').html('<a href="' + txRef.key + '">$' + tx.total + ' <small>' + tx.currencyCode + '</small></a>');
        $('.main ul').append($item);
      });
    });
  }
</script>

问题是,如果我将页面打开足够长的时间,.once() 会被多次调用(每 2-3 小时一次)。这是javascript库上的错误吗?已知问题?是不是我做错了什么或者有什么误解?

【问题讨论】:

  • 什么叫onAuthCompleted()?因为如果那是基于 Firebase 身份验证onAuthStateChanged() 回调,它将在访问令牌刷新时每小时调用一次。

标签: javascript firebase firebase-realtime-database


【解决方案1】:

正如@Frank van Puffelen 在评论中指出的那样,问题出在调用onAuthCompleted(usr) 的方法上:

firebaseApp.auth().onAuthStateChanged(function(user) {
  if (user) {
    if (typeof onAuthCompleted == 'function') { 
      onAuthCompleted(user); 
    }
  } else {
    console.log('User is not logged in. Cannot start session.');
  }
}, function(error) {
  console.log(error);
});

每小时调用一次onAuthStateChanged() 以刷新会话导致再次调用onAuthCompleted() 从而再次注册.once() 方法一次(每隔〜小时)。这导致了奇怪的感知行为。

我可以确认.once() 按预期工作,这是我对onAuthStateChange() 工作方式的误解。

谢谢,

【讨论】:

    猜你喜欢
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2019-05-31
    • 2019-06-29
    相关资源
    最近更新 更多