TypeError:undefined不是对象(评估'_asyncStorage.AsyncStorage.setItem')

时间:2019-07-30 13:10:35

标签: react-native asyncstorage

我正在这样导入AsyncSorage:

import { AsyncStorage } from '@react-native-community/async-storage'

在我的代码中,我正在执行以下操作:

AsyncStorage.setItem('locale', locale)

这:

AsyncStorage.getItem('user').then((value) => {

他们都给我以下错误:

TypeError:未定义不是对象(正在评估'_asyncStorage.AsyncStorage.setItem')

TypeError:未定义不是对象(正在评估'_asyncStorage.AsyncStorage.getItem')

当我从'react-native'导入AsyncStorage时,没有问题,只是说应该从'@ react-native-community'导入AsyncStorage,因为不推荐使用'react-native'的AsyncStorage。 / p>

PS:我知道我应该在AsyncStorage之前使用await,但这不能解决问题。

我的@ react-native-community / async-storage版本如下: "@react-native-community/async-storage": "^1.6.1"

我已经尝试卸载并重新安装@ react-native-community / async-storage依赖关系,

我尝试在它前面放一个等待,但这只是给我同样的错误

我试图用Google搜索它,但是没有找到任何解决方案。

该屏幕的完整代码:

import React from 'react';
import { View, Image, NativeModules } from 'react-native';
import { AsyncStorage } from '@react-native-community/async-storage'
import { styles } from '../../components/Styles.js';
import { GEOLocation } from '../../scripts/GEOLocation';
import Moment from 'moment/min/moment-with-locales';

export default class SplashScreen extends React.Component {


  constructor(props) {
    super(props);
    this.geo = new GEOLocation();
    this.setLocale();
    this.bootstrapAsync();
  }


  bootstrapAsync = async () => {

    this.geo.grantAccess()

    AsyncStorage.getItem('user').then((value) => {
      const user = JSON.parse(value);
      this.props.navigation.navigate(user ? 'App' : 'Auth');
    })
  };

  setLocale = () => {
    const deviceLocale = NativeModules.I18nManager.localeIdentifier
    var locale;

    if (deviceLocale.includes('_')) {
      var language = deviceLocale.split('_')[0]
      var country = deviceLocale.split('_')[1].toLowerCase()

      locale = language + '-' + country
    } else {
      locale = deviceLocale
    }

    if(Moment.locales().indexOf(locale) > -1 ) {
      console.log('device locale')
      AsyncStorage.setItem('locale', locale)
    } else {
      console.log('default locale')
      AsyncStorage.setItem('locale', 'en')
    }
  }


  render() {
    return (
      <View style={styles.container}>
        <Image style={styles.leImage} source={require('../../../assets/logo_icon.png')} />
      </View>
    )
  }
}

1 个答案:

答案 0 :(得分:10)

这里是使用正确的导入方法的方法。

import AsyncStorage from '@react-native-community/async-storage';

此模块不会导出为react-native,因此它不能带有方括号。

react-native模块中使用

import { AsyncStorage } from 'react-native';