问题描述
我正在Redux动作中将Firebase Listener与 on
方法一起使用,以在屏幕中获取数据.这是下面的我的redux操作代码:
I'm using Firebase Listener with on
method in Redux action for getting data in a Screen. Here is my redux action code below:
export const getSelectedProjectDetail = (groupUid, projectUid) => dispatch => {
dispatch({
type: GET_SELECTED_PROJECT_DETAIL_START,
});
firebase.database().ref('/groups/' + groupUid + '/projects/' + projectUid).on('value', (mainSnap) => {
firebase
.database()
.ref('/users/' + mainSnap.val().creator.uid)
.on('value', snapshot => {
const messagesList = _.map(mainSnap.val().messages, (val, uid) => ({ ...val, uid }));
for (let index = 0; index < messagesList.length; index++) {
// eslint-disable-next-line no-loop-func
firebase.database().ref('/users/' + messagesList[index].author.uid).on('value', function (childSnapshot) {
messagesList[index] = {
...messagesList[index],
author: {
...messagesList[index].author,
name: childSnapshot.val().displayName,
email: childSnapshot.val().email,
},
};
if (index === messagesList.length - 1) {
const selectedProjectDetail = {
...mainSnap.val(),
creator: { ...mainSnap.val().creator, name: snapshot.val().displayName },
messages: _.reverse(messagesList),
};
dispatch({
type: GET_SELECTED_PROJECT_DETAIL_SUCCESS,
payload: selectedProjectDetail,
});
NavigationService.navigate('ProjectDetail');
}
});
}
});
});
};
问题是,当我在另一个屏幕上时,如果数据库中有更改,则屏幕会转到带有侦听器的屏幕上.我认为,当我关闭屏幕时,我需要停止听众.我该如何使用Firebase功能或其他功能停止它们?
Problem is that when there are changes in my database while i am on another screen, screen passes to the one with listener. I think, i need to stop listeners when i close the screen. How can i stop them with Firebase functions or any?
推荐答案
如果在redux中添加侦听器,例如
if you add listener in redux be like
const myRef = '/users/' + messagesList[index].author.uid
firebase.database().ref(myRef).on('value',
function (childSnapshot) {
messagesList[index] = {
...messagesList[index],
author: {
...messagesList[index].author,
name: childSnapshot.val().displayName,
email: childSnapshot.val().email,
},
};
并且您需要将该 myRef
保存在redux存储上
And you need to save that myRef
on redux store
在组件卸载时,在componentWillUnmount中您可以调度其他操作,您可以通过以下方式删除监听器 firebase.database().ref('myRef').off('value',回调)
那时,您可以从redux存储中访问 myRef
变量
At the time when the component unmounts, in componentWillUnmountYou can dispatch another action andYou can remove the listener by firebase.database().ref('myRef').off('value', callback)
at that time you can acess myRef
variable from your redux store
这篇关于当我传递到另一个屏幕时,如何停止Firebase Listener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!