Issue
I have enabled backandroid to show logout alert in home screen. Problem is even though screen navigated away from home screen. still Logout alert coming. basic back navigation is also disabled.
HomeScreen.js
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this._handleback);
}
componentWillUnmount() {
//Forgetting to remove the listener will cause pop executes multiple times
BackHandler.removeEventListener('hardwareBackPress', this._handleback);
}
_handleback = () => {
Alert.alert(i18N.t('alertHeader'), i18N.t('logoutqHeader'), [
{
text: i18N.t('yes'), onPress: () => { this.props.navigation.navigate('login'); }
},
{ text: i18N.t('cancel'), onPress: () => { return true; }, style: 'cancel' },
], { cancelable: false });
return true;
};
I want to show logout alert only in home screen. In other screens I want to follow basic back navigation. Please let me know how to solve this.
Solution
Following approach helped me to solve it.
In Homescreen I have included alert normally like in the question.
For the rest of the screens I have included goback() of navigation.
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
It achieved my requirement of showing alert in home screen and going back in other screens with this approach.
Answered By - Kartiikeya
Answer Checked By - Gilberto Lyons (JavaFixing Admin)