我试图使用异步存储进行用户身份验证来决定将呈现哪个屏幕,所以当我从异步存储中获取数据时返回给我未定义有人可以帮助我吗?
我的获取代码:
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);
进一步引用
关于react-native - 异步存储无法在 React Native 上设置或获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45341020/