当应用程序在后台运行时存储时间戳。反应本机

时间:2018-07-23 14:22:07

标签: javascript react-native redux

已编辑:我想在react native应用程序进入后台时存储时间戳,以查看是否需要重新登录。我使用异步存储在appstate功能的帮助下将时间戳保存在设备上。 但是getItem和setItem代码从不执行。知道为什么吗?

componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
}
 _handleAppStateChange = (nextAppState: any) => {

    if (
        this.state.appState.match(/inactive|background/) &&
        nextAppState === 'active'
    ) {
        this.getTime();
        this.checkTimeStamp();
        console.log(this.state.time, 'time var');
        console.log('app is active, and has been in the background');
    } else if (
        this.state.appState == 'active' &&
        nextAppState == 'active'
    ) {
        this.setTime();
        this.checkTimeStamp();
        console.log(this.state.time, 'time var');
        console.log('app is active, and just opened.');
    } else {
        this.setTime()
            //sets the timestamp
        console.log('app in background or closed');
    }
    this.setState({ appState: nextAppState });
};

async setTime() {
    let seconds = this.generateTime();
    try {
        const val = await AsyncStorage.setItem('time', seconds.toString());
        this.setState({ time: Number(val) });

    } catch (error) {
        console.error('onRejected function called: ' + error);
    }
}

async getTime() {
    let please = await AsyncStorage.getItem('time');
    this.setState({ time: Number(please) });
    console.log(this.state.time, 'time var');

}

1 个答案:

答案 0 :(得分:2)

看看AppState endpoint 它允许您侦听“活动” /“背景”状态的更改。