Reputation: 817
I have this code where I have the back button on android devices disabled for one screen of my app, when I change to another screen the back button gets enabled again in componentWillUnmount
, however if I move to another screen by pressing the button below it does not run componentWillUnmount
so I decided to add the removeEventListener
to the onPress
aswell. For some reason this does not work, if I push the button it does navigate to my other screen, however it does not remove the event listener.
Also:
Yes I have also tried placing the code in the onPress
in it's own function, this made no difference however, it still switched screen but did not re-enable my back button.
componentWillMount()
{
BackAndroid.addEventListener('hardwareBackPress', () => {return true});
}
componentWillUnmount()
{
BackAndroid.removeEventListener('hardwareBackPress');
}
render(){
return(
<Button
style={styles.button}
onPress={() => {BackAndroid.removeEventListener('hardwareBackPress'); this.props.navigation.navigate('home');}}>
</Button>
);
}
Upvotes: 0
Views: 7249
Reputation: 1950
The signature of BackAndroid.addEventListener and BackAndroid.removeEventListener are not the same. Hence, hardwareBackPress has not been removed in ComponentWillUnmount. Please try something like this:
constructor() {
this._onBack = this._onBack.bind(this)
}
_onBack() {
return true;
}
componentWillMount()
{
BackAndroid.addEventListener('hardwareBackPress', this._onBack);
}
componentWillUnmount()
{
BackAndroid.removeEventListener('hardwareBackPress', this._onBack);
}
Upvotes: 2