我正在构建一个 Android 应用程序,但我正在努力使用 AsyncStorage。我想创建一个函数,将一个键作为输入并将该项目还给我。我的问题是,当我调用此函数时,它返回 { _40: 0, _65: 0, _55: null, _72: null } 而不是我要查找的值。
这是我的代码:
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: undefined is not a function (evaluating 'this.setstate({ title: response })')
最佳答案
您看到的是由标记为 async
的函数返回的 Promise
对象。您需要在调用函数时使用 await
,或者将值视为 promise 并使用 then
和 catch
。例如:
await save();
const response = await fetch();
console.log(response);
或
save()
.then(() => fetch())
.then(response => console.log(response));
此外,请记住,您不应该在渲染函数中使用异步函数。在上面的代码中,您需要将 fetch()
函数的结果放入组件状态。
关于android - React native/Trouble with AsyncStorage 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46408439/