First, sorry for my english.
I'm trying to handle the hardware android back button using React Navigation and BackHandler. But, I can't really use goBack() react-navigation function.
So, I got a class androidBackButton.js that is :
import {BackHandler, Alert} from 'react-native';
const handleAndroidBackButton = callback => {
BackHandler.addEventListener('hardwareBackPress', () => {
callback();
return true;
});
};
const removeAndroidBackButtonHandler = () => {
BackHandler.removeEventListener('hardwareBackPress', () => {});
}
const exitAlert = () => {
Alert.alert(
"Quitter l'application",
"Êtes vous sûr de vouloir quitter l'application ?",
[
{text: 'Non', style: 'cancel'},
{text: 'Oui', onPress: () => BackHandler.exitApp()},
]
);
};
export {handleAndroidBackButton, removeAndroidBackButtonHandler, exitAlert};
To use it, I use componentDidMount and componentWillUnmount in a screen like that :
componentDidMount() {
handleAndroidBackButton(this.props.navigation.goBack());
}
componentWillUnmount() {
removeAndroidBackButtonHandler();
}
But.. Like you certainly know, I can't call a props in componentDidMount because I'll got a warning that is 'Can't perform a React State update on an unmounted component.'. Even if the action is only call when I push the android hardware back button, it try to define it when I load the component. So, this is not working.
By the way, I try to define it like that :
componentDidMount() { handleAndroidBackButton(() => {this.props.navigation.goBack()}); }
By this way, no warning is displaying. But when I click the hardware button, nothing is happening..
So yes, somebody has an idea of what is happening ? Is there a way to achieve this without creating any errors ?
Thanks so much !