如何检测React Native应用程序何时关闭(未暂停)?反应原生文档

问题描述 投票:38回答:2

我到处寻找,找不到答案。如何检测用户何时尝试关闭我的React Native应用程序(如在进程正在运行,并且他们手动管理他们的应用程序并强制退出它)。我希望在发生这种情况时添加注销功能,但无法找到检测它的方法。 AppState似乎只检测应用程序何时进入和退出后台。

mobile reactjs react-native
2个回答
17
投票

看起来您可以检测到先前的状态并将其与下一个状态进行比较。您无法检测到应用程序正在关闭而不是进入后台,我可以在网上找到,但您可以检测到它是inactive(已关闭)还是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
投票

作为一种简单的方法,我们可以在根组件内部使用componentWillUnmount()来检测应用程序是否已关闭。因为Root组件仅在app关闭时卸载。 :)

© www.soinside.com 2019 - 2024. All rights reserved.