我面临的问题是从本机中的函数返回值。它是一个全局函数,不在任何类中。我正在为var分配返回值。但值总是未定义的。下面是功能代码片段。
var userLoggedIn= (function (){
AsyncStorage.getItem("isLoggedIn").then((login) => {
var loggedIn = login;
console.log("Logged In " + loggedIn); // getting correct value
return loggedIn;
}).done();
})();
console.log("userLoggedIn" + userLoggedIn); // this is undefined
const IntialScreen = AppNavigator(loggedIn); 导出默认的IntialScreen;
请检查我在这里做错了什么。我是新手对本机和JavaScript做出反应,所以我可能做错了或者我不了解JavaScript的一些概念
答案 0 :(得分:1)
在处理异步调用时应该返回一个promise。在你的case.userLoggedIn是未定义的,因为它执行时没有等待AsyncStorage.get item()返回的响应
var userLoggedIn= (function (){
return new Promise((resolve, reject) => {
AsyncStorage.getItem("isLoggedIn").then((login) => {
var loggedIn = login;
console.log("Logged In " + loggedIn); // getting correct value
resolve(loggedIn);
}).done();
})
})();
根据OP的澄清更新
export default function(callback){
userLoggedIn.then((loggedIn)=>{
//do whatever you want to do with it
const IntialScreen = AppNavigator(loggedIn);
callback(IntialScreen);
})
};
某个组件
import InitialScreen from './somefile';
InitialScreen((loginData)=>{
//loginData will have what you wanted to export
});
答案 1 :(得分:0)
var userLoggedIn = false;
(function(){
AsyncStorage.getItem("isLoggedIn").then((login) => {
var loggedIn = login;
console.log("Logged In " + loggedIn); // getting correct value
}).done(function() {
userLoggedIn= loggedIn;
});
})();
希望这有帮助