'How to remove listner in the right way in react native navigation with class components
when I use removeListner
function to remove the listner on navigation, I got a warning about that and that the remove not works correctly.
componentDidMount() {
this.props.navigation.addListener('focus', this.props.didFocus);
this.props.navigation.addListener('blur', this.props.didBlur);
}
componentWillUnmount() {
this.props.navigation.removeListener('focus',this.props.didFocus);
this.props.navigation.removeListener('blur',this.props.didBlur);
}
}
in old versions of Navigation it was used like the following example :
subscribe : NavigationEventSubscription;
componentDidMount() {
this.subscribe = this.props.navigation.addListener('didFocus', this.props.didFocus);
}
componentWillUnmount() {
if(this.subscribe){
this.subscribe.remove();
}
}
}
Solution 1:[1]
removeListener
works fine.
I got a warning about that
You need to say what warning you got if you're asking for help.
Another way is to use the function returned by addListener
.
unsubscribe?: () => void;
componentDidMount() {
this.unsubscribe = this.props.navigation.addListener('focus', this.props.didFocus);
}
componentWillUnmount() {
this.unsubscribe?.()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | satya164 |