google-cloud-firestore - 在 MobX 中正确同步 Firestore 集合
问题描述
我正在尝试从 MobX 中的 firestore 同步数据,但 onSnapshot 方法有问题。
我正在使用流和生成器来做到这一点。但我不确定如何从 onSnapshot 处理正确的 sub/unsub 监听器
export class MyStore {
@observable myItems: Array<MyModel> = [];
sub: any //??
constructor(){
this.sync();
}
sync = flow(function*(this: MyStore) {
const dbRef = firestore().collection('items');
try {
yield this.sub = dbRef.onSnapshot((data: any)=>{ //??
// do something with data
// const items = ...
this.setItems(items);
})
} catch(error) {
// error handling
}
})
@action setItems = (items: MyModel[]) => {
this.myItems = items;
};
}
以及如何纠正退订?还有一个问题——只有第一次同步调用才能捕获错误。当我在 firestore 中更改某些内容时,它会更改 myItems,但它会跳过 try catch 范围(它在 onSnapshot 方法的回调中运行 onlny)。如何“尝试/捕捉”firestore 上的每一个变化?
解决方案
当你打电话时,onSnapshot
你会得到订阅的句柄。当您将该句柄作为函数调用时,它会取消订阅进一步的更新。
所以在你的情况下:
this.sub();
推荐阅读
- sql - ID号(数据库)可以有小数点吗?
- ruby-on-rails - structure.sql 文件中的 search_path 被 rails db:migrate 修改
- mdadm - mdadm 进程 100% CPU
- r - 根据 rhandsontable 值显示特定列的总和
- c# - 在 Visual Studio 项目中跳过 Active Directory 身份验证
- mysql - ProgrammingError:1054(42S22):“字段列表”中的未知列“Lucas_Johnson”
- javascript - 使用 JavaScript 测试输入是韩语还是中文的正确方法是什么?
- pyqt5 - 在 PyQt5 中的 QTextEdit 中更改选项卡的缩进空间
- dji-sdk - 如何在 DJI-SDK 中使用触发器?
- sql - SQL 到 JPQL 加入请求