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

前端 未结 7 498
囚心锁ツ
囚心锁ツ 2020-12-13 04:10

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 s

相关标签:
7条回答
  • 2020-12-13 04:19

    This is how I've achieved it:

      componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
      }
      componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
      }
      handleBackButtonClick() {
        BackHandler.exitApp();
        return true;
      }
    
    0 讨论(0)
  • 2020-12-13 04:20

    This npm module helped me with the same issue - react-native-exit-app

    import RNExitApp from 'react-native-exit-app';
    ...
    RNExitApp.exitApp();
    ...
    
    0 讨论(0)
  • 2020-12-13 04:29

    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

    0 讨论(0)
  • 2020-12-13 04:30

    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.

    0 讨论(0)
  • 2020-12-13 04:30

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 04:33

    on terminal you can either press

    > ctrl+c
    

    or you can simply kill all node

    > killall node
    
    0 讨论(0)
提交回复
热议问题