ComponentWillUnmount取消订阅Firestore
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()?如果我尝试将其保存在状态内,则会抛出一个错误,即取消订阅不是一个函数。
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 })
});
}
以上是关于ComponentWillUnmount取消订阅Firestore的主要内容,如果未能解决你的问题,请参考以下文章