【问题标题】:Store timestamp when the app is in background. React native当应用程序在后台时存储时间戳。反应原生
【发布时间】:2018-07-23 14:22:06
【问题描述】:

已编辑:我想在 react 本机应用程序进入后台时存储时间戳,以查看是否需要重新登录。在 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');

}

【问题讨论】:

  • 你能解决这个问题吗?

标签: javascript react-native redux


【解决方案1】:

看看 AppState https://facebook.github.io/react-native/docs/appstate 它允许您监听“活动”/“背景”状态变化。

【讨论】:

  • 是的。听起来这就是要走的路。试图将其简化很多。知道如何查看应用程序是否即将关闭,并运行最后一秒的代码吗?
  • 好吧,componentWillUnmount 是这样做的地方,但为什么要在即将卸载的组件上设置状态?
  • 因为,我想设置应用程序进入后台时的时间戳,而不是之前。
猜你喜欢
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2022-10-08
  • 1970-01-01
  • 2020-06-20
  • 2016-07-17
  • 2021-04-24
  • 1970-01-01
相关资源
最近更新 更多