美文网首页React Native开发经验集Android技术知识
React Native 网络获取数据后,listView显示数

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

作者: 曾经_f745 | 来源:发表于2017-08-18 16:35 被阅读0次

    用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显示数

        本文链接:https://www.haomeiwen.com/subject/ojmarxtx.html