我有这段代码,可以在添加新的子级时侦听实时数据库中的更改。
mUserRef = firebase.database().ref("Messages").child(conversation);
mUserRef.on("child_added", snapshot => {
const message = {
key: snapshot.key,
...snapshot.val()
};
this.onReceive(message);
});
,当收到新的孩子添加到数据库参考
时,将触发此代码let cy = this;
firebase
.database()
.ref("LastMessages")
.child(key)
.once("value")
.then(function(snapshot) {
//...some code
});
问题是,当我使用 componentWillUnmount
时,我无法取消订阅实时侦听器退订代码
constructor(props) {
super(props);
this.state = {
ready: false,
messages: []
};
}
_isMounted = false;
componentDidMount = async () => {
this._isMounted = true;
}
async retriveMessages(conversation) {
let cy = this;
cy.setState({
ready: true
});
let mUserRef = null;
if (this._isMounted) {
mUserRef = firebase
.database()
.ref("Messages")
.child(conversation);
mUserRef.on("child_added", snapshot => {
const message = {
key: snapshot.key,
...snapshot.val()
};
this.onReceive(message);
});
} else {
mUserRef.child(conversation).off("child_added");
}
}
componentWillUnmount() {
this._isMounted = false;
}
我尝试过的解决方案:
Unsubscribing from Firebase Realtime Database
componentwillunmount to unsubscribe from firestore
how to remove firebase database listener...
How to stop Firebase Listener when i pass to another screen?
答案 0 :(得分:3)
componentWillUnmount()
在卸载和销毁组件之前立即被调用。在此方法中执行任何必要的清除,例如使计时器无效,取消网络请求或清除在componentDidMount()中创建的所有订阅。
因此请执行以下操作:
componentWillUnmount() {
mUserRef.off("child_added");
this._isMounted = false;
}