一:步骤
-1: 定义请求数据接口,在componentDidMount() 中调用
-2:在constructor() 中定义listview的数据源以及改变策略
-3:在数据请求完成,改变数据源,使用this.setState() 来更新保存数据
-4:定义一个请求数据时的view
-5:渲染数据,根据loaded来判断数据是否加载完成
-6:listview的renderRow()是渲染数据源中的一条数据
二:
import React, {Component} from 'react';
import {
AppRegistry,
View,
Text,
Image,
StyleSheet,
ListView,
} from 'react-native’;
//请求url:
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
class FristProject extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2)=>row1 != row2,
}),
//定义不重复请求数据
loaded: false,
};
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL).then((response)=>response.json())
.then((responseData)=> {
//更新数据
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true
});
})
.done();
}
renderLodingView() {
return (
<View style={styles.container}>
<Text>
loading............
</Text>
</View>
);
}
renderMove(movie) {
return (
<View style={styles.container}>
<Image source={{uri:movie.posters.thumbnail}} style={styles.thumbnial}/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
render() {
if (!this.state.loaded) {
return this.renderLodingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMove}
/>
);
}
}
var styles = StyleSheet.create({
container: {
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5fcff'
},
thumbnial: {
width: 53,
height: 81,
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center'
}
}
)