2017-09-25 11 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() ; 

しかし、私はまだエラーを取得:例外TypeError:未定義の関数ではありません( 'this.setstate({title:response})'を評価する)

+0

[非同期呼び出しから応答を返すにはどうすればいいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-電話) –

+0

まずはそのことです。第二に、 'fetch()'呼び出しに 'key'の値を渡さないことが原因である可能性があります。私はこれを再現しようとしますが、これら2つのことがあなたの出発点です。 –

+0

誰かが答えて、私の最初の勘違いが正しいように見えます。それは重複している。答えと私がリンクしているものの両方を読む時間を取ってください。これは、今後も多くの同様のエラーを避けるのに役立ちます。 –

答えて

2

表示されているのはPromiseオブジェクトで、asyncと表示された関数です。関数を呼び出すときにawaitを使用するか、またはその値を約束として扱い、thencatchを使用する必要があります。たとえば:

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

または

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

また、あなたがレンダリング関数内で非同期関数を使用すべきではないことに注意してください。上のコードでは、fetch()関数の結果をコンポーネントの状態にすることができます。

+0

ありがとう、これは私を助けた。 – Audeo

関連する問題