AsynStorage似乎无法在我的物理设备上运行

时间:2017-03-21 00:21:43

标签: javascript react-native android-emulator react-native-android asyncstorage

我的react-native应用程序在模拟器上完美运行。但是当我将它转移到实际设备时,AsyncStorage的回调似乎不起作用。我甚至尝试发布apk。但没有运气。

我要存储文件中的项目' Attraction.js'像这样。

async addToRecentSearches(){
try{
  var recentSearches = JSON.parse(await AsyncStorage.getItem("@travelGeo:recentSearches"));
  var hasAMatch = recentSearches.find((el)=>{
    return el.name.toLowerCase() === this.props.navigation.state.params.attraction.name.toLowerCase();
  })

  console.log("hasAMatch", hasAMatch);

  // add the attraction to the AsyncStorage if the attraction doesnt already exist
  if(!hasAMatch){
    if(recentSearches && recentSearches.length===3){
      /***push attraction and pop one***/
      recentSearches.unshift(this.props.navigation.state.params.attraction);
      recentSearches.pop();
      AsyncStorage.setItem("@travelGeo:recentSearches", JSON.stringify(recentSearches) );

    }else if(recentSearches && recentSearches.length<3){
      /***push this attraction to the array***/
      recentSearches.unshift(this.props.navigation.state.params.attraction)

      AsyncStorage.setItem("@travelGeo:recentSearches", JSON.stringify(recentSearches) );
     }else{
      /***add this attraction to the storage***/
      let arr = [];
      arr.unshift(this.props.navigation.state.params.attraction);

      AsyncStorage.setItem("@travelGeo:recentSearches", JSON.stringify(arr));
    }
  }
}catch(e){
  console.log(e);
} }

并且我从componentDidMount

调用此异步函数
componentDidMount(){
 this.addToRecentSearches();
}

然后我试图从不同的路线(Weather.js)中检索数据。

async componentWillMount(){
try {
  let recentSearches = JSON.parse(await AsyncStorage.getItem("@travelGeo:recentSearches"));
  console.log(recentSearches);
  this.setState({testGet:recentSearches[0].name})
  for(var i=0;i<recentSearches.length;i++){
    if(recentSearches[i].location){
      let response = await getWeatherByLocation(recentSearches[i].location.latitude,recentSearches[i].location.longitude);

      recentSearches[i].currentWeatherData = response;
    }
  }

  console.log("recentSearchesWithWeatherData", recentSearches);
  this.setState({recentSearches:recentSearches});

} catch (e) {
  console.log(e);
}
}

(我在componentWillMount()中使用async仅用于测试目的。) 我使用{recentSearches:recentSearches}状态来渲染数据。

此代码在模拟器中完美运行。但似乎并没有在实际的设备上工作。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

好吧,我是个白痴......这是一个非常愚蠢的错误。 错误是从这一行抛出的

var recentSearches = JSON.parse(await AsyncStorage.getItem("@travelGeo:recentSearches"));

我一直试图从尚未设置的异步存储中检索一个值。

但是,在模拟器中,当我第一次编写代码时,我必须设置"@travelGeo:recentSearches"密钥。因此,它确实可以在模拟器上运行,但不能在物理设备上运行。

相关问题