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>
)
我正在尝试获取AsyncStorage中的值,但我不断收到错误:undefined不是一个函数(评估'this.state.data.map)。我搜索类似主题已有一段时间,但没有找到任何解决方案。有人可以教我一个正确的例子吗?谢谢
答案 0 :(得分:1)
如果您已通过这种方式存储数据
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>
);
};
答案 1 :(得分:0)
在 AsyncStorage 之前尝试等待,类似于或内联
componentWillMount (){
const rest = await AsyncStorage.getItem('restaurants');
}