AppState更改时将DateTime值存储在AsyncStorage中

时间:2019-05-28 04:18:14

标签: react-native react-native-android react-native-ios asyncstorage

我试图在应用程序状态更改时存储DateTime值。假设应用程序在后台,我想将DateTime的值存储在AsyncStorage中,当应用程序处于活动状态时,我想计算时间差。但是我作为返回值获得的承诺为空。我的RN版本是56.0,有人可以帮我吗?

StoreDate = async () => {
        await AsyncStorage.setItem('date', new Date());
      };

      retrieveDate = async () => 
      {
        try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return JSON.parse(value);

    }
          catch(error){
            Alert.alert(error);
          }
      };

     if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then((filter) => {
            console.log("filter",filter);
            console.log("getDateTime",getDateTime);
          });
    }

**尝试使用getItem检索值时返回空承诺**

enter image description here

1 个答案:

答案 0 :(得分:0)

您应该将日期存储为字符串,并且在检索时将其更改为“日期”,例如

StoreDate = async () => {
    await AsyncStorage.setItem('date', new Date().getTime());
  };

retrieveDate = async () => {
    try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return new Date(parseInt(value));
    }
    catch(error){
        Alert.alert(error);
    }
};

if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then(() => {
        this.retrieveDate().then(data => {
           console.log('retrieve data ' , data)
        })
      });
}