Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackHandler does not go back more than 1 screen

I have this code on each of my screens. Pressing the android back button goes back 1 screen. Pressing android back button again does not do anything. Expected result would be to keep going back as long as there are more screens in the stack. What's missing?

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => {
        this.props.navigation.goBack();
        return true;
    });
}

componentWillUnmount() {
  BackHandler.removeEventListener('hardwareBackPress')
}
like image 480
Justin Lok Avatar asked Jul 18 '17 11:07

Justin Lok


1 Answers

After some trial and error, this code works as expected. I believe my initial code was not actually removing the event listener.

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backPressed);
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.backPressed);
}

backPressed = () => {
    this.props.navigation.goBack();
    return true;
}
like image 82
Justin Lok Avatar answered Dec 07 '22 05:12

Justin Lok