当AppState在react-native中处于非活动状态时,如何设置一些要运行的功能

时间:2019-06-19 13:51:10

标签: react-native

当AppState处于非活动状态并且我不知道该怎么办时,我尝试向数据库中的变量添加一个数字

AppState.addEventListener('change', () => this.handleAppStateChange())
handleAppStateChange(){
    if(AppState.currentState === 'inactive'){
        addIncome().then().catch(error => {})
    }
}

1 个答案:

答案 0 :(得分:0)

您应在addremovecomponentDidMountcomponentWillUnmount AppState更改侦听器:

state = {lastAppState: AppState.currentState};

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

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

另外,您还需要保存最新的AppState的状态,并在AppState更改时进行检查,以找出更改为inactive的时间:

handleAppStateChange = (nextAppState) => {
  if (
    this.state.lastAppState === 'active' &&
    nextAppState.match(/inactive|background/)
  ) {
    // your app state changes to inactive
  }

  this.setState({lastAppState: nextAppState});
};
相关问题