Firebase:何时使用onSnapshot

时间:2020-01-03 12:41:05

标签: javascript google-cloud-firestore

因此,我知道如果用户正在查看可由其他用户更新的页面,则应该使用onSnapshot使前端和后端保持同步。但是,假设用户正在查看只有他才能更新的页面,例如显示一些个人信息的页面。

假设我有此字符串let someData = "Some string",该字符串仅在一个用户可以更新的页面上显示。现在,该用户想要更新该字符串中的数据。因此,firestore文件可能会像这样更新:

const db = firestore();
const someValue = "Some other string"  //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue})

现在,数据更改显然应该显示在UI中。

这是我的问题。鉴于只有用户可以在此页面上看到数据的事实,更新UI的正确方法是什么?

const db = firestore();
db.onSnapshot(snapshot=>someData = snapshot.data().data);
const someValue = "Some other string"  //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue});

OR

const db = firestore();
const someValue = "Some other string"  //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue});
someData = someValue;

我的意思是我应该独立于数据库更新UI还是作为对数据库文档更改的响应。

希望我可以澄清我的问题。预先感谢!

1 个答案:

答案 0 :(得分:0)

如果您在文档上附加了快照侦听器,并且编写了用于更新该文档的代码,则该侦听器将立即被调用(甚至在服务器上发生更改之前)。无需在侦听器外部更新UI,只需让侦听器立即响应更新并更新UI本身即可。