9

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

我的获取代码:

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

5 回答 5

13

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

进一步参考

于 2017-07-27T04:07:56.657 回答
2

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

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

AsyncStorage.getItem('mobileNumber', (error, result) => {
  this.setState({
    loginMobileNo: result,
  });
于 2019-02-27T12:26:25.030 回答
1

将 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;
    }
}
于 2019-10-24T17:22:13.747 回答
0

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

var myStr = JSON.stringify(yourData);

用键设置项目

AsyncStorage.setItem('key', myStr);

获取项目

var value = AsyncStorage.getItem('key');
于 2018-07-04T17:35:30.407 回答
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')
        }
    });
}
于 2018-09-17T10:02:29.137 回答