【问题标题】:React native / Trouble with AsyncStorage get item使用 AsyncStorage 获取项目反应本机/故障
【发布时间】:2018-03-06 14:44:07
【问题描述】:

我正在构建一个 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 (evalating 'this.setstate({ title: response })')

【问题讨论】:

  • 第一个猜测是。其次,这可能是由于没有将 key 的值传递给您的 fetch() 调用。我会尝试重现这一点,但这两件事是你的起点。
  • 看起来有人回答了,我的第一个预感是正确的。这是一个副本。花一些时间阅读答案和我链接的答案。它将帮助您避免将来出现许多类似的错误。

标签: android react-native


【解决方案1】:

您看到的是由标记为async 的函数返回的Promise 对象。您需要在调用函数时使用await,或者将值视为承诺并使用thencatch。例如:

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

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

另外,请记住,您不应该在渲染函数中使用异步函数。在上面的代码中,您需要将 fetch() 函数的结果放入组件状态。

【讨论】:

  • 谢谢,这对我有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2021-09-28
  • 2016-09-12
相关资源
最近更新 更多