React Native AsyncStorage 没有获得价值 [英] React Native AsyncStorage not getting the value
本文介绍了React Native AsyncStorage 没有获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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").我一直在搜索类似的主题,但没有找到任何解决方案.有人可以告诉我一个正确的例子吗?谢谢
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
推荐答案
如果您曾以这种方式存储数据
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>
);
};
这篇关于React Native AsyncStorage 没有获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文