用fetch()的方法获取网络数据,ListView来显示数据。
完整Demo:
import React, {Component} from 'react'
import {AppRegistry, StyleSheet, Image, Text, View, ListView} from 'react-native'
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
const styles = StyleSheet.create({
container: {
flex:1,
flexDirection:'row',
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF'
},
thunbnail:{
width:100,
height:80,
},
});
class TestURL extends Component{
constructor(props) {
super(props)
this.state={
dataSource:null
}
}
render() {
if (!this.state.dataSource) {
return this.renderLoadingView();
}
return this.renderMovie();
}
fetchData() {
var myRequest = new Request(REQUEST_URL);
myRequest.method='GET';
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
fetch(myRequest).then((response) => response.json())
.then((responseData) => this.setState({dataSource:ds.cloneWithRows(responseData.movies)}))
.catch((error) => {console.log(error)})
}
componentDidMount() {
this.fetchData();
}
renderLoadingView() {
return(
<View style={styles.container}>
<Text >
loading...
</Text>
</View>
);
}
renderMovie() {
return(
<ListView
dataSource={this.state.dataSource}
renderRow={(movie)=>this._renderRow(movie)}
/>
)
}
_renderRow(movie) {
return (
<View style={{flexDirection:'row'}}>
<Image source={{uri:movie.posters.thumbnail}} style={styles.thunbnail}/>
<Text>{movie.title}</Text>
</View>
)
}
}
AppRegistry.registerComponent('Demo', ()=>TestURL);
1. 定义样式:
const styles = StyleSheet.create({
container: {
flex:1,
flexDirection:'row',
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF'
},
thunbnail:{
width:100,
height:80,
},
});
2. 数据加载完成前后UI的渲染:
render() {
if (!this.state.dataSource) {
return this.renderLoadingView();
}
return this.renderMovie();
}
如果listview的DataSource是null的话,会加载loading的动画,如果不为空的话,就会显示Listview
3.显示loading...的UI
renderLoadingView() {
return(
<View style={styles.container}>
<Text >
loading...
</Text>
</View>
);
}
4.加载完数据后,显示ListView的代码:
renderMovie() {
return(
<ListView
dataSource={this.state.dataSource}
renderRow={(movie)=>this._renderRow(movie)}
/>
)
}
_renderRow(movie) {
return (
<View style={{flexDirection:'row'}}>
<Image source={{uri:movie.posters.thumbnail}} style={styles.thunbnail}/>
<Text>{movie.title}</Text>
</View>
)
}
}
UI效果: