react-native- 网络访问

一:步骤
-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'
        }

    }
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值