1. 程式人生 > >fetch 請求列表ListView

fetch 請求列表ListView

item all reat int mar master listview 添加 ont

//練習二 電影列表(網絡請求數據)
/*
* 展示電影列表
* 邏輯:
* 未獲得數據時:顯示等待頁面
* 獲得數據時: 顯示電影列表頁面
*
* 需要給state添加一個屬性,用於記錄下載狀態
*
* http://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample
* */

var MovieList = React.createClass({
getInitialState:function () {
//ListView相關
let ds = new ListView.DataSource({rowHasChanged:(r1,r2) => r1!==r2 });

//
return{
load:false //數據是否下載成功的標識
};
},
//下載數據
getData:function () {
let url = "http://www"
fetch(url)
.then((response) => {
return response.json()
})
.then((responseData) => {
//刷新組件,重新渲染組件,展示ListView
//得到新的數據, 更新dataSource
this.setState({
loaded:true,
//ListView
dataSource:this.state.dataSource.cloneWithRows(responseData.movies)
});

})
.catch((error) => {
alert(error)
})

},
render:function () {
//如果未請求到數據,顯示 "等待加載" 頁面
if(!this.state.loaded){
return this.renderLoadingView();
}

//電影列表
return(
<ListView
style={styles.listView}
dataSource={this.state.dataSource}
initialListSize={10} //多少行
renderHeader={this._renderHeader}
renderRow={this._renderRow}
renderSeparator={this._renderSeparator}
/>

);
},
//組件掛載完成
componentDidMount:function () {
//組件掛載後,開始下載數據
this.getData();
},

//等待加載頁面
renderLoadingView:function () {
return(
<View style={styles.loadingContainer}>
<Text style={styles.loadingText}>Loading movies...</Text>
</View>
);
},
//渲染row
_renderRow:function (movie) {
return(
<View style={styles.rowContainer}>
<Image
style={styles.rowImage}
source={{uri:movie.url}}
/>
<View style={styles.rowTextContainer}>
<Text style={styles.rowTitle}></Text>
</View>
</View>
)
},
//渲染頭部
_renderHeader:function () {
return(
<View style={styles.header}>
<Text style={styels.headerText}>List 頭部</Text>
<View style={styles.headerSeparator}></View>
</View>
)
},
//渲染分割線
_renderSeparator:function (sectionID:number,rowID:number) {
var style = {
height:1,
backgrounColor:"#CCCCCC"
};
return(
<View style={style} key={sectionID+rowID}></View>
)

}




});

var styels = StyleSheet.create({
//loading
loadingContainer:{
flex:1,
marginTop:25,
backgrounColor:‘cyan‘,
justifyContent:‘center‘,
alignItems:‘center‘
},
loadingText:{
fontSize:22,
textAlign:‘center‘,
marginLeft:11,
marginRight:22

},
//ListView Row
rowContainer:{
flexDirection:"row",
padding:5,
alignItems:"center",
backgrounColor:"#F5FCFF"
},
rowImage:{
width:33,
height:81,
backgrounColor:"gray"
},
rowTextContainer:{
flex:1,
marginLeft:10,
},
rowTitle:{
marginTop:3,
fontSize:18,
textAlign:"center"
},
//ListView Header
header:{
height:44,
backgrounColor:"#F5FCFF"
},
headerText:{
flex:1,
fontSize:18,
fontWeight:"bold",
textAlign:"center"
},
headerSeparator:{
height:1,
backgrounColor:"black"

},
//ListView
listView:{
marginTop:25,
backgrounColor:"#F5FCFF"

}


});

fetch 請求列表ListView