How do I exit/shut down a React Native app?

2019-01-14 05:52发布

If my React Native app fails to connect to its backend, I show an Alert with an OK button. If this happens, there's no point in the app continuing to run, so I'd like to shut it down when the button is clicked. How do I do this?

I suspect the key is in AppRegistry but the docs are a bit scant.

5条回答
虎瘦雄心在
2楼-- · 2019-01-14 06:37

I am answering the question too late, but i thought the way i have chosen might help someone, so I am answering this question.

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

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

backPressed = () => {
  Alert.alert(
    'Exit App',
    'Do you want to exit?',
    [
      {text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
      {text: 'Yes', onPress: () => BackHandler.exitApp()},
    ],
    { cancelable: false });
    return true;
}
查看更多
走好不送
3楼-- · 2019-01-14 06:41

For Android, Use BackAndroid to exit the App:

import React, {
    BackAndroid,
} from 'react-native';

BackAndroid.exitApp();
查看更多
不美不萌又怎样
4楼-- · 2019-01-14 06:42

This is how I've achieved:

  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  handleBackButtonClick() {
    BackHandler.exitApp();
    return true;
  }
查看更多
forever°为你锁心
5楼-- · 2019-01-14 06:53

There's no react-native specific way to do this today. You'd have to accomplish this from the native side of things.

Further, are you developing for iOS? Apple has stated that apps should not close themselves.

查看更多
唯我独甜
6楼-- · 2019-01-14 06:53

Write a native module that performs the following actions when called:

IOS:

exit(9);

ANDROID:

((YourApplication) self.getApplicationContext()).kill();

...EDIT...

Or just use the one I created: https://www.npmjs.com/package/react-native-exit-app

查看更多
登录 后发表回答