简体   繁体   中英

React Native - Stack navigation when back handler is used

I have a simple app with a stack navigator. Which navigates like

Screen A --> Screen B --> Screen C --> Screen D

I have added a back handler in Screen B like this

componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

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

It is working as expected on Screen B. When navigated to C or D, the hardware button won't cause navigation back to B or C respectively. Instead, it seems to fire the handleBackButtonClick in Screen B. How can I avoid this?

React Navigation keeps the previous screens rendered. So you need to make sure that the back handler is only enabled in the focused screen.

The official docs cover it.

For v4: https://reactnavigation.org/docs/en/custom-android-back-button-handling.html

For v5: https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html

I think in your case the code could be simplified:

handleBackButtonClick = () => {
  // If this screen is not focused, don't do anything
  if (!this.props.navigation.isFocused()) {
    return false;
  }

  // Do what you're doing
}
``

I've faced the same issue,ie backhandler was trigeering the previous screens backhandler code.

SO what i did was checking for any existing backhandlers and then manually removing it in componentDidMount, rather than trusting the componentWillUnmount for that component..

componentDidMount(){
if (this.backHandler) // checking if backhnalder exists from previous screen
    this.backHandler.remove();//removing it
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => { this.handleBackButton() });// adding the new backhandler

}

Hope this helps, otherwisae feel free to ask any doubts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM