在 React Native 中使用 AsyncStorage 的 GetItem 不起作用 [英] GetItem with AsyncStorage in React Native is not working

查看:91
本文介绍了在 React Native 中使用 AsyncStorage 的 GetItem 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in react native and getting the bind value at index 1 is null when I am trying to get data from AsyncStorage in react-native below is my code.

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');
    }
}

请帮忙.

推荐答案

您可以使用这种格式:

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') 

AsyncStorage 需要一些时间来获取数据,因此它会返回一个 promise,直到该值可用.您必须调用 then() 函数并从那里获取值.then() 函数中的任何内容都会在从存储中检索值后调用.

AsyncStorage takes some time to fetch data so it returns a promise until the value is available. You have to call the then() function and get the value from there. Anything inside the then() function is called after the value is retrieved from storage.

这篇关于在 React Native 中使用 AsyncStorage 的 GetItem 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆