How to detect when a React Native app is closed (not suspended)?

后端 未结 2 625
Happy的楠姐
Happy的楠姐 2020-12-02 09:58

I have looked everywhere and cannot find an answer to this. How can I detect when a user is trying to close my React Native app (as in the process is running, and they manua

相关标签:
2条回答
  • 2020-12-02 10:28

    As a simple method , we can use componentWillUnmount() inside the root component for detect the app is closed. Because Root component Unmount only when app is closed. :)

    0 讨论(0)
  • 2020-12-02 10:32

    Looks like you can detect the previous state and compare it to the next state. You can't detect that the app is closing vs going into the background, from what I can find online, but you can detect if it was inactive (closed), or in the background.

    Example from React Native Docs

    import React, {Component} from 'react'
    import {AppState, Text} from 'react-native'
    
    class AppStateExample extends Component {
    
      state = {
        appState: AppState.currentState
      }
    
      componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
      }
    
      componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
      }
    
      _handleAppStateChange = (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
          console.log('App has come to the foreground!')
        }
        this.setState({appState: nextAppState});
      }
    
      render() {
        return (
          <Text>Current state is: {this.state.appState}</Text>
        );
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题