我的项目中有聊天功能。当有人发送消息时,我使用推送更新数据库。
我定义了一个名为 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/