问题
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');
}
});
}
});
});
};
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?
回答1:
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,
},
};
And you need to save that myRef
on redux store
At the time when the component unmounts, in componentWillUnmount
You can dispatch another action and
You can remove the listener by
firebase.database().ref('myRef').off('value', callback)
at that time you can acess myRef
variable from your redux store
来源:https://stackoverflow.com/questions/56485590/how-to-stop-firebase-listener-when-i-pass-to-another-screen