我有这段代码可以在添加新 child 时监听实时数据库中的变化。
mUserRef = firebase.database().ref("Messages").child(conversation);
mUserRef.on("child_added", snapshot => {
const message = {
key: snapshot.key,
...snapshot.val()
};
this.onReceive(message);
});
当接收到添加到数据库中的新 child 时,将触发此代码 ref
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?
最佳答案
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().
因此执行以下操作:
componentWillUnmount() {
mUserRef.off("child_added");
this._isMounted = false;
}
关于javascript - React Native 无法对未安装的组件 firebase 执行 React 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172066/