简体   繁体   中英

Android back button handler react native router flux

I have one react native app in which I have used react native router flux, My scene falls this way

  1. Splash
  2. Login
  3. Dashboard
  4. On click of Dashboard icon it goes to notification screen

Initially when app is loaded everything goes smooth. But when I click on dashboard icon, it navigates to Notification screen and when I press Android back button it goes to Dashboard screen as I have written BackHandler and in which I have written Actions.pop()

Now in dashboard I have written BackHandler with checking count ie if Back button is pressed two times and making it exit from the app, but the problem is it works only if I haven't navigated to Notification screen, when I navigate to Notification screen and then press back button it navigates to dashboard but when I press back button again on dashboard, it just makes me navigate to login screen and from there to splash screen.

What I want is even if I navigated to Notification screen, and pressed back button I should navigate to Dashboard and on Dashboard back button click (2 times) it should exit app without redirecting to login & splash screen.

My code is this way for Dashboard screen-

constructor(props) {
    super(props);
    this.backCount = 0;
    this.onHandleBackButton = this.handleBackButton.bind(this);


}
async componentWillMount() {

    BackHandler.addEventListener('hardwareBackPress', this.onHandleBackButton);

}
handleBackButton() {
    console.log("back button - dashboard")

    if (this.backCount == 1) {
        BackHandler.exitApp();
        this.backCount = 2;
        return; // exit
    }
    else if (this.backCount == 0) {

        Toast.show("Press again to exit", Toast.SHORT);
        this.backCount++;

        setTimeout(() => {
            if (this.backCount != 2)
                this.backCount = 0;
        }, 2000)

        return true;
    }
}

Code for Notification screen -

constructor(props) {
    super(props);
    this.onHandleBackButton = this.handleBackButton.bind(this);

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

}
handleBackButton() {


    Actions.pop();
   return true;
}

I have tried several ways with type={ActionConst.RESET} and other too.

The first thing you have to do is navigate and clear your splash and login screen. Because currently what's happening is your screens are popped and splash and login are already in the stack. And secondly, put a check condition in the dashboard that if the routname is your dashboard then only double exit condition should execute rest it should not work. I think it'll work.

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