我正在尝试使用feed来在本机上创建一个应用程序。在主屏幕上,我去获取数据:
fetchData() {
firebase.database().ref(`/posts/${group}`).on('value', async snapshot => {...}
}
例如,当我想对帖子发表评论时,我首先使用不同的查询将数据推送到firebase中,例如:
export const likeComment = (...) => {
firebase.database().ref(`/posts/${group}/${post}`).update
({
updatedAt: firebase.database.ServerValue.TIMESTAMP
});
firebase.database().ref(`/posts/${group}/${post}/lastComments`).set(...);
但是我意识到我的第一个函数fetchData被调用了3次。然后我将查询分组为:
let updates = {}
updates[`/posts/${group}/${post}/lastComments`] = {...};
updates[`/posts/${group}/${post}`] = { ... };
firebase.database().ref().update(updates);
然后,fetchData被调用了两次。
我想知道这是否是最好的方法,为什么我的函数fetchData仍然被调用两次。谢谢你的帮助
从有限的代码很难看出来,但是我的猜测是fetchData
实际上并没有被多次调用,而是snapshot
在您更新Firebase数据库时触发。
您在代码中说.on('value', async snapshot =>
要设置一个侦听器的部分,以便在值更改时随时向您发送更新。
所以我的猜测是您的三个调用是:
.on( snapshot
当你调用监听器发射update
.on( snapshot
听众再次射击,当你调用set
这种基于推送的数据库工作流程是Firebase的主要优势之一。如果您只想获取一次数据而又不获取实时更新,则可以致电.once(
而不是.on(
https://firebase.google.com/docs/database/web/read-and-write
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句