React Native AsyncStorage not getting the value

2019-08-21 10:11发布

问题:

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');
}