reactjs - ComponentWillUnmount 取消订阅 Firestore
问题描述
我正在尝试使用 ComponentWillUnmount 停止侦听 Firebase Firestore 集合更改:
https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener
var unsubscribe = db.collection("cities")
.onSnapshot(function (){
// Respond to data
// ...
});
// Later ...
// Stop listening to changes
unsubscribe();
但是,我无法访问此 unsubscribe(); 因为它是在 ComponentWillMount 中声明的,我需要在 ComponentWillUnmount 中使用它。
如何在 ComponentWillUnmount 中使用这个 unsubscribe()?如果我尝试将它保存在 state 中,它会抛出 unsubscribe 不是函数的错误。
constructor() {
super();
this.state = {
notes: [],
unsubscribe: null
};
this.getNotes = this.getNotes.bind(this);
}
componentDidMount(){
this.getNotes();
}
componentWillUnmount(){
var unsubscribe = this.props.unsubscribe;
unsubscribe();
}
getNotes = () => {
const db = this.props.firestore;
const colRef = db.collection("users").doc(this.props.uid)
.collection("notes");
let notes = [];
const that = this;
// Realtime updates listener
var unsubscribe = colRef.orderBy("timestamp", "asc")
.onSnapshot(function(querySnapshot) {
var notes = [];
querySnapshot.forEach(function(doc) {
notes.push(
{ id: doc.id,
body: doc.data().body}
);
});
that.setState({ notes })
});
this.setState({ unsubscribe })
}
抛出:
Uncaught TypeError: unsubscribe is not a function
解决方案
您可以将取消订阅引用保存在类实例 ( this
) 上:而不是做var unsubscribe
,this.unsubscribe = [...]
然后再从类实例中读取它:this.unsubscribe()
componentDidMount(){
this.getNotes();
}
componentWillUnmount(){
this.unsubscribe();
}
getNotes = () => {
const db = this.props.firestore;
const colRef = db.collection("users").doc(this.props.uid)
.collection("notes");
let notes = [];
const that = this;
// Realtime updates listener
this.unsubscribe = colRef.orderBy("timestamp", "asc")
.onSnapshot(function(querySnapshot) {
var notes = [];
querySnapshot.forEach(function(doc) {
notes.push(
{ id: doc.id,
body: doc.data().body}
);
});
that.setState({ notes })
});
}
推荐阅读
- javascript - 在 Angular 6 中显示来自 api 的数据的问题
- scala - Spark RDD 的文件名使用
- javascript - 您可以从自定义 Kentico 全局事件处理程序中执行 javascript 吗?
- c++ - 在打印方法中我的二叉树中难以打印数据
- xml - 寻找 xpath - 我误解了一些基本的东西
- c++ - C++ 为什么 const X& 可以被函数修改?
- mysql - MySQL JOIN LIMIT 动态查询优化
- angular - 我使用 typeof 来识别对象的类型时遇到 TS2639 错误
- firebase - 如何删除 Source.CACHE 中的特定 Firestore 文档?
- node.js - 如何设置 Twilio 工人统计数据的开始和结束日期?