简体   繁体   中英

How to detect an application in the kill app on react native?

I want to change the state data from the API when the application is killed by the user.

I have tried using the componentWillUnmount to change data when the application closes, I also use the AppState

  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!')
    }
    this.setState({ appState: nextAppState })
  }


I want that when the application is killed by the user, it can change the state automatically.

nextAppState === 'inactive' or checking if background does not tell you if the app is "Killed" (swiped out) or not.

Because when the native layer is killed then the javascript engine is killed as well. So there is no way to tell javascript that the app is killed.

If you just want to initialize something after the app is killed, you can fire some function inside constructor or componentDidMount of a base component which you know that it will be mounted only once for your app.

added: Now we may (maybe prefer to) use useEffect(()=>{}, []) instead of examples above.

If you really want to make sure the app is killed before, maybe you can store nextAppState into some persisted store and check if the value matched one of inactive or background since the app state will not be changed on the initial startup of the app.

Try This:

componentDidMount() {
   AppState.addEventListener('change', 
   this.handleAppStateChange);
  }

componentWillUnmount() {
  AppState.removeEventListener('change', this.handleAppStateChange);
}

handleAppStateChange = (nextAppState) => {
   if (nextAppState === 'inactive') {
   console.log('the app is closed');
  }    
 }

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