React Native 网络获取数据后,listView显示数据

用fetch()的方法获取网络数据,ListView来显示数据。

完整Demo:

[html]view plaincopy

import React, {Component} from 'react'

import {AppRegistry, StyleSheet, Image, Text, View, ListView} from 'react-native'

varREQUEST_URL='https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

conststyles=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() {

varmyRequest=newRequest(REQUEST_URL);

myRequest.method='GET';

constds=newListView.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(

loading...

);

}

renderMovie() {

return(

dataSource={this.state.dataSource}

renderRow={(movie)=>this._renderRow(movie)}

/>

)

}

_renderRow(movie) {

return (

{movie.title}

)

}

}

AppRegistry.registerComponent('Demo', ()=>TestURL);

下面进行详细介绍:

1. 定义样式:

[html]view plaincopy

conststyles=StyleSheet.create({

container: {

flex:1,

flexDirection:'row',

justifyContent:'center',

alignItems:'center',

backgroundColor:'#F5FCFF'

},

thunbnail:{

width:100,

height:80,

},

});

2. 数据加载完成前后UI的渲染:

[html]view plaincopy

render() {

if (!this.state.dataSource) {

return this.renderLoadingView();

}

return this.renderMovie();

}

如果listview的DataSource是null的话,会加载loading的动画,如果不为空的话,就会显示Listview

3.显示loading...的UI

[html]view plaincopy

renderLoadingView() {

return(

loading...

);

}

4.加载完数据后,显示ListView的代码:

[html]view plaincopy

renderMovie() {

return(

dataSource={this.state.dataSource}

renderRow={(movie)=>this._renderRow(movie)}

/>

)

}

_renderRow(movie) {

return (

{movie.title}

)

}

}

你可能感兴趣的:(React Native 网络获取数据后,listView显示数据)