2017-07-27 30 views
2

我試圖使用異步存儲的用戶身份驗證來決定將顯示哪個屏幕,因此當我從異步存儲獲取數據返回給我undefined有人可以幫助我嗎?異步存儲無法正常工作設置或繼續React Native

我的獲取代碼:

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

回答

3

alert(login);永遠是不確定的,因爲AsyncStorage.getItem在本質上是異步的意思警報(登錄)您會收到之前首先叫來自AsyncStorage.getItem的值

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

進一步參考

+0

感謝的人是工作! –

+0

@LuizFernandoSousaCamargo歡迎您 –

相關問題