React Native中带有AsyncStorage的GetItem无法正常工作

时间:2019-05-17 07:18:28

标签: android react-native mobile asyncstorage

我是react native的新手,当我尝试从下面的react-native中的AsyncStorage获取数据时,获取索引1的绑定值是null。

Alert.alert(
        'Info',
        'React AsyncStorage',
        [
            {text: 'Get Data',onPress: () => this.getValue('name'),},
            {text: 'Save Data', onPress: () => this.saveValue('name', 'abc'),}
        ],
        {cancelable: false},
        );


async saveValue(key:String, value:bool) {
     AsyncStorage.setItem(key, value);
     Alert.alert('Data', 'saving');         
}
async getValue(key) {         
    // try {
    //     await AsyncStorage.getItem(Constant.SHOW_INTRO).then((value) =>
    //         console.log(`AsyncStorage GET for Constant.SHOW_INTRO: "${value}"`));

    // } catch (error) {
    //     Alert.alert('Error', 'Error retrieving data');
    // }

    try {
        const value = await AsyncStorage.getItem(key)
        console.log(`AsyncStorage GET for "${key}": "${value}"`);
    } catch (error) {
        Alert.alert('Error', 'Error retrieving data');
    }
}

请帮助。

2 个答案:

答案 0 :(得分:0)

尝试通过这种方式进行操作:

async getValue(key){
  try {
    const value = await AsyncStorage.getItem(key)
    console.log(`AsyncStorage GET for "${key}": "${value}"`);
  } catch (error) {
    Alert.alert('Error', 'Error to retrieve data');
  }
}

答案 1 :(得分:0)

您可以使用以下格式:

setData = (value) => {
    // if value is an Object use this: value = JSON.stringify(value)
    // if value is a number use this: value = value.toString()
    AsyncStorage.setItem('myKey', value, () => {
        console.warn('Done!')
    })
}

getData = () => {
    AsyncStorage.getItem('myKey').then(storage => {
        console.warn(storage)
    }).catch(e => console.warn(e))
}

然后:

this.setData('sample text')