javascript - Firebase 网站 : Method doesn't trigger first time inside of child_added

标签 javascript firebase firebase-realtime-database

我的项目中有聊天功能。当有人发送消息时,我使用推送更新数据库。

我定义了一个名为 renderChatUI 的方法。

我这样定义一个监听器:

firebase.database().ref(`USERS/${Database.getNestedData('UID')}/UserClass/${grade}/${subject}/Topics/${key}/Chats`).on('child_added', (snapshot) => {
  console.log('Hello');
  this.renderChatUI(UID, grade, subject, key);
})

因此,每次将任何消息添加到此路径时,我的聊天 UI 都会重新呈现。

child_added 代码块执行完美,但 renderChatUI() 方法第一次不会触发(当我添加第一条消息时)。添加第二条消息时,聊天 UI 会使用第一条消息重新呈现,添加第三条聊天 UI 时会使用第二条消息重新呈现,依此类推...!

我不知道出了什么问题。感谢您的帮助。

最佳答案

要让child-added在添加到数据库后触发,那么可以使用完成回调,例如:

 firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  }, function(error) {
    if (error) {
      // The write failed...
    } else {
      // Data saved successfully!
      firebase.database().ref(`USERS/${Database.getNestedData('UID')}/UserClass/${grade}/${subject}/Topics/${key}/Chats`).on('child_added', (snapshot) => {
         console.log('Hello');
         this.renderChatUI(UID, grade, subject, key);
       })
    }
  });
}

来自docs :

The optional completion callback that is called when the write has been committed to the database. If the call was unsuccessful, the callback is passed an error object indicating why the failure occurred.

关于javascript - Firebase 网站 : Method doesn't trigger first time inside of child_added,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56730576/

相关文章:

javascript - 无法通过 react 在 firebase 中删除项目

javascript - JavaScript 到 MVC : Controller Variable Passing via Actionlink

javascript - 如何检查数组对象的属性是否与另一个对象数组中的值之一匹配

javascript - 如何从 Firestore 检索 map 并对其进行迭代?

java - 应用程序因空对象引用而崩溃

swift - 在 Swift 中使用 Firebase 查询最新条目

javascript - OpenX 异步标签

javascript - 如何批量插入CouchDB文档?

javascript - 在 React 应用程序和 Firebase 数据库之间同步状态

firebase - Firebase 托管能否提供来自 Cloud Functions 的缓存数据?