React-Native AsyncStorage:TypeError:无法读取未定义的属性“setItem”

Hen*_*ryM 4 javascript react-native asyncstorage

我正在学习react-native并尝试使用AsyncStorage. 我正在使用此代码来存储数据:

_storeData = async (token) => {
    console.log("store token");
    console.log(token);
    try {
      await AsyncStorage.setItem('token', token);
    } catch (error) {
      // Error saving data
      console.log(error);
    }
  }
Run Code Online (Sandbox Code Playgroud)

调用它:this._storeData(res.token);

但它给了我这个错误:

> TypeError: Cannot read property 'setItem' of undefined
>     at LoginOrCreateForm._callee$ (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:138096:71)
>     at tryCatch (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21408:19)
>     at Generator.invoke [as _invoke] (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21583:24)
>     at Generator.prototype.(anonymous function) [as next] (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21451:23)
>     at tryCatch (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21408:19)
>     at invoke (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21484:22)
>     at blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:21514:13
>     at tryCallTwo (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:22690:7)
>     at doResolve (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:22854:15)
>     at new Promise (blob:http://localhost:8081/21ec2746-a3c9-4c68-937f-ee50c63a6d58:22713:5)
Run Code Online (Sandbox Code Playgroud)

有人可以帮助解决我做错的事情吗?谢谢

小智 7

我面临着同样的问题。

\n

如果你正在使用

\n

React Native 0.60+

\n

然后按照https://react-native-async-storage.github.io/async-storage/docs/install/在您的项目中安装 AsyncStorage 。

\n

"@react-native-async-storage/async-storage": "^1.15.17"

\n

安装和链接完成后,将其导入到您的项目中:

\n
import AsyncStorage from \'@react-native-async-storage/async-storage\';\n
Run Code Online (Sandbox Code Playgroud)\n

确保:

\n
import AsyncStorage from \'@react-native-async-storage/async-storage\';\xe2\x9c\x85\nimport { AsyncStorage } from \'@react-native-async-storage/async-storage\'; \xe2\x9d\x8c\n
Run Code Online (Sandbox Code Playgroud)\n