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}

)

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一. 简介 一个核心组件,用于高效地显示一个可以垂直滚动的变化的数据列表。最基本的使用方式就是创建一个ListVi...
    飞奔的小马阅读 5,242评论 0 2
  • 前言 本文有配套视频,可以酌情观看。 文中内容因各人理解不同,可能会有所偏差,欢迎朋友们联系我。 文中所有内容仅供...
    珍此良辰阅读 5,472评论 13 7
  • 前言 学习本系列内容需要具备一定 HTML 开发基础,没有基础的朋友可以先转至 HTML快速入门(一) 学习 本人...
    珍此良辰阅读 14,570评论 11 24
  • 前言 本文有配套视频,可以酌情观看。 文中内容因各人理解不同,可能会有所偏差,欢迎朋友们联系我。 文中所有内容仅供...
    珍此良辰阅读 4,852评论 0 6
  • 我们公司的工资多数以“合提”的方式来挣取提成。多数人会认为,那岂不是销售好的人很吃亏,其实不然,我们有绩效考核。每...
    王朋彦阅读 2,622评论 0 0

友情链接更多精彩内容