firestore onSnapshot执行两次 [英] firestore onSnapshot executing twice
问题描述
我的firestore onSnapshot()函数被调用两次.
My firestore onSnapshot() function is being called twice.
let user = firebase.firestore().collection('users').doc(userID).onSnapshot
({
next: (documentSnapshot: firebase.firestore.DocumentSnapshot) =>
{
this.userArray.push(documentSnapshot as User);
console.log(documentSnapshot);
//here
},
error: (firestoreError: firebase.firestore.FirestoreError) =>
{
console.log(firestoreError);
//here
}
});
我也尝试过在 https://firerefer.google .com/docs/firestore/query-data/listen#detach_a_listener ,在//此处注释中包含user(),但无济于事.
I have also tried subscribing like in https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener by including user() at the //here comment but to no avail.
我该如何修改,以使该功能仅执行一次,即每次仅推送一个用户对象,而不是两次.
How can I modify such that the function only executes one time, i.e. push only one user object per time instead of twice.
推荐答案
我不知道这是否与您的问题有关.如果有人在使用
I don't know if this is related to your question. If one is using
firebase.firestore.FieldValue.serverTimestamp()
给文档加上时间戳,然后onSnaphot将触发两次.这似乎是因为将新文档添加到数据库时,onSnapshot将触发,但是serverTimestamp尚未运行.几毫秒后,serverTimestamp将运行并更新您的文档=> onSnapshot将再次触发.
to give a document a timestamp, then onSnaphot will fire twice. This seem to be because when you add a new document to your database onSnapshot will fire, but the serverTimestamp has not run yet. After a few milliseconds serverTimestamp will run and update you document => onSnapshot will fire again.
我想在onSnapshot触发之前添加一小段延迟时间(例如0.5秒左右),但是我找不到执行此操作的方法.
I would like to add a small delay before onSnapshot fires (say 0,5s or so), but I couldn't find the way to do this.
您还可以为onCreate事件创建服务器端功能,我相信这可以解决您的问题.也许您的userArray.push-action更适合在服务器端执行.
You can also make a server side function for onCreate event, I believe that would solve your problem. Maybe your userArray.push-action would be more suitable to execute in server side.
这篇关于firestore onSnapshot执行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!