React Native AsyncStorage not getting the value

会有一股神秘感。 提交于 2019-12-24 23:27:46

问题


constructor(props) {
  super(props);
  this.state = { data: '' } ;
}

componentWillMount = () => AsyncStorage.getItem('restaurants').then((value) => this.setState({data: value}))

    return (
  <View>
  {this.state.data.map((item) => {
    return (
      <View>
        <Text> {item.name} </Text>
        <Text> {item.time} </Text>
      </View>
    )
  })
  }
  </View>
)

I am trying to get the value in the AsyncStorage, but i keep getting the error: undefined is not a function(evaluating 'this.state.data.map). I been searching the similar topic for a while but I did not find any solution to it. Can someone show me an correct example to do it? Thanks


回答1:


If You Have stored data in this way

  
  storeData = async () => {
  
    try {
      var data ={ 
       restaurants: [
        {
          name: 'MacD ',
          time: "Morning"
        },
        {
          name: 'PizzaHouse',
          time: "Evening"
        }
      ]
     }
     await AsyncStorage.setItem('restaurants', JSON.stringify(data.restaurants))
     
    } catch (error) {
      // Error saving data
    }
  }
  
constructor(props) {
  super(props);
  this.state={
    fetchingData: true,
    data: []
  }   
}

getData =  async()=>{
  try {
    data = await AsyncStorage.getItem('restaurants');
    this.setState({fetchingData: false , data:JSON.parse(data)})
  } catch(error){
     console.log(error)
  }
}

componentDidMount(){
  this.getData();
}

renderRestaurant(){
  return this.state.data.map((item) => {
    return (
      <View>
        <Text> {item.name} </Text>
        <Text> {item.time} </Text>
      </View>
    )
  })

}  

render() {
  return (
    <View style={{width:200, height:200, justifyContent:'center', alignItems:'center', backgroundColor:"blue"}}>
      {this.state.fetchingData ? null : this.renderRestaurant()}
    </View>
  );
};



回答2:


Try await before AsyncStorage, similar to that or inline

componentWillMount (){
  const rest = await AsyncStorage.getItem('restaurants');
}


来源:https://stackoverflow.com/questions/51799924/react-native-asyncstorage-not-getting-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!