异步存储无法设置或启用React Native

时间:2017-07-27 03:45:25

标签: react-native asyncstorage

我试图使用异步存储来进行用户身份验证以决定将呈现哪个屏幕,这样当我从异步存储中获取数据时返回给我未定义有人可以帮助我吗?

我的代码:

var login;
AsyncStorage.getItem("login").then((value) => {
      login = value;
}).done();
alert(login);

我的设定代码:

const insert_user = (username) => {
  AsyncStorage.setItem("login", username);
  Toast.show({
    supportedOrientations: ['portrait', 'landscape'],
    text: `User registered with success`,
    position: 'bottom',
    buttonText: 'Dismiss'
  });
}

5 个答案:

答案 0 :(得分:10)

alert(login);将始终未定义,因为AsyncStorage.getItem本质上是异步的,这意味着在从AsyncStorage.getItem

接收值之前首先调用alert(login)
AsyncStorage.getItem("login").then((value) => {
      alert(value); // you will need use the alert in here because this is the point in the execution which you receive the value from getItem.
    // you could do your authentication and routing logic here but I suggest that you place them in another function and just pass the function as seen in the example below.
});

// a function that receives value
const receiveLoginDetails = (value) => {
    alert(value);
}
// pass the function that receives the login details;
AsyncStorage.getItem("login").then(receiveLoginDetails);

进一步参考

答案 1 :(得分:1)

从'react-native'导入{AsyncStorage};

AsyncStorage.setItem('mobileNumber', phoneNumber.number);

AsyncStorage.getItem('mobileNumber', (error, result) => {
  this.setState({
    loginMobileNo: result,
  });

答案 2 :(得分:0)

最后,当我在设置项目时使用StrigyFy时,AsyncStorage.getItem('foo')可以工作。

var myStr = JSON.stringify(yourData);

使用按键设置项目

AsyncStorage.setItem('key', myStr);

获取物品

var value = AsyncStorage.getItem('key');

答案 3 :(得分:0)

使用“ react-native”:“ 0.56.0”:-

使用以下内容创建一个名为“ Pref.js”的文件。 (Pref.js就像一个用于使用AsyncStorage设置和获取数据的全局文件,因此您可以在任何.js文件中使用。)

//---- Pref.js ---->
import { AsyncStorage, Alert } from "react-native"

export const kUserName = 'user_name';
export const kUserID = 'user_id';


export const setData = async (strKey, item) => {
    let value = JSON.stringify(item)
    if (value) {
        AsyncStorage.setItem(strKey, value);
    }
}

export const getData = (strKey, callback = (response1) => { }) => {
    AsyncStorage.getItem(strKey).then((value) => {
        callback(value)
    });
}

---------在“ index.js”文件中使用以上文件---------> (导入具有正确路径的Pref.js文件)

import * as Pref from '../../Pref/Pref'   //IMPORTANT: set your file path.

onLoginClick = () => {

    // Set data in AsyncStorage using "Pref.js" file. "Pref.kUserName" is from Pref.js file:
    Pref.setData(Pref.kUserName, 'Hello World')

    // Get data from AsyncStorage using "Pref.js" file.
    Pref.getData(Pref.kUserName, (value) => {
        if (value) {
            Alert.alert(`Welcome ${value}`)
            //this.props.navigation.push('Home')
        }
    });
}

答案 4 :(得分:0)

将AsyncStorage与async和await一起使用的完整内容如下

import { getItem as localStorageGetItem, setItem as localStorageSetItem } from 'services/localStorage';
async loginHandler (){
     localStorageSetItem(ACCESS_TOKEN, response.accessToken);
     var token = await localStorageGetItem(ACCESS_TOKEN);
}

localStorage.js文件

import AsyncStorage from '@react-native-community/async-storage';

export const getItem = async(item) => {
    try {
        const value = await AsyncStorage.getItem(item);
        return JSON.parse(value);
    } catch (error) {
        return null;
    }
};

export const setItem = async(item,value)=>{
    try {
        await AsyncStorage.setItem(item, JSON.stringify(value));
    } catch (error) {
        console.log("SetItem error ",error)
        return null;
    }
}