【问题标题】:AsyncStorage doesn't seems to work on my physical deviceAsyncStorage 似乎无法在我的物理设备上运行
【发布时间】:2017-03-21 00:21:43
【问题描述】:

我的 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} 状态来呈现数据。

此代码在模拟器中运行良好。但似乎不适用于实际设备。任何帮助将非常感激。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    然而,在模拟器中,当我第一次编写代码时,我必须设置"@travelGeo:recentSearches" 键。因此,它确实适用于模拟器,但不适用于物理设备。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2022-01-12
      • 2020-06-11
      • 2015-11-09
      • 1970-01-01
      相关资源
      最近更新 更多