【发布时间】:2019-02-21 17:19:17
【问题描述】:
我正在尝试从 URL 获取数据,然后将其存储在 React Native 的 AsyncStorage 中。
这是“魔法”发生的屏幕:
class CardsScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
}
}
componentDidMount() {
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
isLoading: false,
dataSource: responseData,
});
})
.catch((error) => {
console.log(error)
});
}
render() {
if (netStatus) {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator/>
</View>
)
} else {
let data = this.state.dataSource.map((val, key) => {
return <View key={key} style={styles.itemWrapper}>
<View style={styles.titleWrapper}>
<Text style={styles.content}>{val.type}</Text>
<Text style={styles.title}>{val.title}</Text>
<Text style={styles.content}>{val.date}</Text>
</View>
<View style={styles.imageWrapper}>
<Image
style={styles.image}
source={{uri: val.image}}
/>
</View>
<View style={styles.contentWrapper}>
<Text style={styles.content}>{val.adress}</Text>
<Text style={styles.content}>{val.text}</Text>
</View>
</View>
})
return (
<ScrollView contentContainerStyle={styles.containerScroll}>
{data}
</ScrollView>
);
}
} else {
return <View style={styles.contentWrapper}>
<Text style={styles.content}>Not connected!</Text>
</View>
}
}
};
如果设备连接到互联网,此代码将打印数据。 我需要做的是如果设备连接到互联网,从 URL 获取数据并将其存储(或覆盖)在 AsyncStorage 中,然后在屏幕上打印数据。如果设备未连接到互联网,只需从 AsyncStorage 打印数据。
这是我从 URL 调用的 .json 示例:
[
{
"type": "Party",
"title": "New party comming to town!",
"adress": "New Yrok",
"date": "20. 4. 2019.",
"image": "https:\/\/some-url.com\/some-image.jpg",
"text": [
"Some description"
],
"_id": "events_1"
}
]
我找不到任何类似的解决方案,所以如果有人有教程可以帮助我解决这个问题,我会很高兴。
编辑(更多解释):
这就是我想做的: 如果设备已连接到 Internet,请使用来自 URL 的数据更新 AsyncStorage,然后在 AsyncStorage 中显示该新数据。如果设备未连接到 Internet,则仅显示 AsyncStorage 的数据。并且有多个“事件”,而不仅仅是示例中的一个。
【问题讨论】:
-
谢谢,你能告诉我怎么做吗?
标签: json react-native fetch asyncstorage