异步存储无法设置或获取 React Native

Async storage not working to set or get on React Native

我正在尝试使用异步存储进行用户身份验证来决定将呈现哪个屏幕,所以当我从异步存储中获取数据时 returns 对我来说是未定义的,有人可以帮助我吗?

我的领取码:

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

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

进一步参考

在我这边AsyncStorage.getItem('foo') 当我在设置项目时使用 StrigyFy 时有效。

var myStr = JSON.stringify(yourData);

用键设置项目

AsyncStorage.setItem('key', myStr);

获取物品

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

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

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

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

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

将 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;
    }
}