代码之家  ›  专栏  ›  技术社区  ›  HenryM

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

  •  2
  • HenryM  · 技术社区  · 6 年前

    我正在学习如何反应并尝试使用 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);
        }
      }
    

    称之为: 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)
    

    2 回复  |  直到 6 年前
        1
  •  3
  •   Sang Huynh    6 年前

    确保你已经准备好了 import { AsyncStorage } from "react-native"

        2
  •  2
  •   amirhosein    6 年前

    因为 AsyncStorage 未定义,请尝试在类的顶部导入此行:

    import { AsyncStorage } from 'react-native'
    
        3
  •  0
  •   T P M ABDULKAREEM    4 年前

    import { useAsyncStorage } from '@react-native-community/async-storage';
    ---
    
    const { getItem, setItem } = useAsyncStorage('@storage_key');
    
      const readItemFromStorage = async () => {
        const item = await getItem();
        setValue(item);
      };
    
      const writeItemToStorage = async newValue => {
        await setItem(newValue);
        setValue(newValue);
      };
    
    

    参考: https://react-native-community.github.io/async-storage/docs/api#useasyncstorage

        4
  •  0
  •   Shah    4 年前
    yarn add @react-native-async-storage/async-storage
    yarn install
    

    import AsyncStorage from "@react-native-async-storage/async-storage";

    资料来源:

    https://react-native-async-storage.github.io/async-storage/docs/api/