问题描述
我正在尝试使用ComponentWillUnmount停止侦听Firebase Firestore集合更改:
I'm trying to use ComponentWillUnmount to stop listening to Firebase Firestore collection changes:
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中使用它.
However, I cannot access this unsubscribe(); since it is declared inside ComponentWillMount and I need to use it in ComponentWillUnmount.
如何在ComponentWillUnmount中使用此unsubscribe()?如果我尝试将其保存在状态内,则会引发错误,指出取消订阅不是函数.
How can I use this unsubscribe() inside ComponentWillUnmount? If I try to save it inside the state it throws an error that unsubscribe is not a function.
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取消订阅
做 this.unsubscribe = [...]
,然后再次从类实例中读取它: this.unsubscribe()
You can save the unsubscribe reference on the class instance (this
): instead of doing var unsubscribe
do this.unsubscribe = [...]
and later just read it from the class instance again: 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 })
});
}
这篇关于ComponentWillUnmount取消订阅Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!