2017-09-25 139 views
2

我正在構建一個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})')

+0

可能重複[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-打電話) –

+0

首先猜測就是這樣。其次,這可能是由於沒有在你的'fetch()'調用中傳遞'key'的值。我會試圖重現這一點,但這兩件事是你的起點。 –

+0

看起來像有人回答,我的第一個預感是正確的。這是重複的。花一些時間閱讀答案和我所鏈接的答案。它可以幫助您避免將來發生許多類似的錯誤。 –

回答

2

您所看到的是標記爲async的函數返回的Promise對象。調用函數時需要使用await,或將該值作爲承諾處理,並使用thencatch。例如:

await save(); 
const response = await fetch(); 
console.log(response); 

save() 
    .then(() => fetch()) 
    .then(response => console.log(response)); 

另外,請記住,你不應該使用異步功能的渲染函數內。在上面的代碼中,您需要將fetch()函數的結果置於組件狀態。

+0

謝謝,這幫助了我。 – Audeo