我正在構建一個Android應用程序,我掙扎着使用AsyncStorage。我想創建一個函數,它將一個鍵作爲輸入並讓我返回項目。我的問題是,當我調用這個函數時,它會返回{_40:0,_65:0,_55:null,_72:null},而不是我正在查找的值。反應本機/麻煩與AsyncStorage獲取項目
這裏是我的代碼:
renderList() {
async function save() {
await AsyncStorage.setItem('Title', 'hello');
}
async function fetch(key) {
const value = await AsyncStorage.getItem(key);
console.log(value) ; // Return hello
return value
}
save() ;
fetch() ;
const reponse = fetch() ;
console.log(reponse) ; // Return { _40: 0, _65: 0, _55: null, _72: null }
return (
<Text style={styles.noteElementTitle}> Aa </Text>
)
}
編輯:
我嘗試這樣做:
async function getBody() {
await save();
const response = await fetch('Title');
console.log(response);
this.setstate({ title : response}) ;
}
getBody() ;
但我仍然得到一個錯誤:類型錯誤:未定義是不是一個函數(評估'this.setstate({title:response})')
可能重複[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-打電話) –
首先猜測就是這樣。其次,這可能是由於沒有在你的'fetch()'調用中傳遞'key'的值。我會試圖重現這一點,但這兩件事是你的起點。 –
看起來像有人回答,我的第一個預感是正確的。這是重複的。花一些時間閱讀答案和我所鏈接的答案。它可以幫助您避免將來發生許多類似的錯誤。 –