如何使用async / await在React Native中使用功能从AsyncStorage检索值

时间:2019-01-16 05:56:36

标签: react-native asyncstorage

我已经创建了prefsManager.js-用于存储和从AsyncStorage检索数据,但是我遇到了一个问题,例如当打印日志时,由于它是Async,它总是返回未定义的状态,但是我想通过函数的调用。

import { AsyncStorage } from 'react-native';
import prefskey from '../utils/constants/prefskeys';

const setValue = async (key, value) => {
    await AsyncStorage.setItem(key, value);
}

const getValue = async (key) => {
    let value = '';
    try {
        value = await AsyncStorage.getItem(key) || 'none';
    } catch (error) {
        // Error retrieving data 
        console.log(error.message);
    }
    return value;
};

const prefsmanager = {
    setValue,
    getValue
}
export default prefsmanager; 

按下按钮时,我在Home.js中使用了此方法。

_handlePress() {

        await prefsManager.setValue(prefskey.username, this.state.username)

        console.log("username =>>", await prefsManager.getValue(prefskey.username)); 

     }

3 个答案:

答案 0 :(得分:1)

您需要像这样在函数上使用async关键字。

    import { AsyncStorage } from 'react-native';
import prefskey from '../utils/constants/prefskeys';

const prefsnamager = {

    setValue: function (key, value) {
        AsyncStorage.setItem(key, value)
    },

    getValue: async (key) => {
        let value = '';
        try {
            value = await AsyncStorage.getItem(key) || 'none';
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
        return value;
    }
}
export default prefsnamager;

调用功能

_handlePress = () => {
        prefsManager.setValue(prefskey.username, this.state.username)

        console.log("username =>>" , prefsManager.getValue(prefskey.username));

     }

答案 1 :(得分:1)

  1. 设置存储值
AsyncStorage.setItem('data','Read Data')
  1. 从存储中获取价值
constructor(props) {
    super(props)       

    this.state = {};
    let self=this;

    //this function is called everytime , when you visit this screen.
    this.__didFocusSubscription = this.props.navigation.addListener('didFocus',payload => {
        AsyncStorage.getItem('data').then((value)=>{
            if(value==null){
                self.setState({count:'no data found'})
            }
            else{
                self.setState({count:value})
            }
        })
    });       
}

答案 2 :(得分:1)

实际上,它类似于网络中的localStorage,但有一点区别。在获取商品时,它是异步运行的。注意以下内容:

AsyncStorage.setItem('key', value);

但是获得它的方式如下:

AsyncStorage.getItem('key')
  .then( value => console.log(value) );