当AppState处于非活动状态并且我不知道该怎么办时,我尝试向数据库中的变量添加一个数字
AppState.addEventListener('change', () => this.handleAppStateChange())
handleAppStateChange(){
if(AppState.currentState === 'inactive'){
addIncome().then().catch(error => {})
}
}
答案 0 :(得分:0)
您应在add
和remove
中componentDidMount
和componentWillUnmount
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});
};