React-Native學習筆記 - 使用ListView加載網(wǎng)絡數(shù)據(jù)

使用ListView加載網(wǎng)絡數(shù)據(jù)

  • 本文采用fecth來進行網(wǎng)絡請求的

創(chuàng)建一個構(gòu)造器

   //js組件的構(gòu)造函數(shù),js的生命周期
    constructor(props) {
        super(props);
         //listView數(shù)據(jù)源
            dataSource: new ListView.DataSource({
                rowHasChanged: function (row1, row2) {
                    return row1 !== row2
                },
                sectionHeaderHasChanged:function (s1, s2) {
                    return s1 !== s2
                },
            }),
            //網(wǎng)絡請求狀態(tài)
            error: false,
            errorInfo: ""
        };
    }

創(chuàng)建網(wǎng)絡請求

var REQUEST_URL = 'https://api.github.com/search/repositories?q=javascript&sort=stars';

 fetchData() {
        //這個是js的訪問網(wǎng)絡的方法
        fetch(REQUEST_URL)
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({
                    //復制數(shù)據(jù)源
                    dataSource: this.state.dataSource.cloneWithRows(responseData.items)
                });
            })
            .catch((error) => {
                this.setState({
                    error: true,
                    errorInfo: error
                })
            })
            .done();

創(chuàng)建Loading View

   //加載等待的view
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <Text>
                    Loading start...
                </Text>
            </View>
        );
    }

創(chuàng)建請求失敗時顯示的view

//加載失敗view
    renderErrorView(error) {

        return (
            <View style={styles.container}>
                <Text>
                    Fail: {error}
                </Text>
            </View>
        );
    }

數(shù)據(jù)顯示view

 //獲取到數(shù)據(jù)加載到控件上
    renderData() {
        return (
            <ScrollView style={
                {
                    paddingTop: 22,
                    paddingLeft: 5,
                    paddingBottom: 5,
                    paddingRight: 5
                }}>
                <Text style={{fontSize: 20}}>data:</Text>
                <ListView dataSource={this.state.dataSource}
                          renderRow={this.renderItemView}/>
            </ScrollView>
        );
    }

    //返回itemView
    renderItemView(item) {
        return (
            <View>
                <Text style={{fontSize: 15, color: 'blue'}}>name: {item.name} ({item.stargazers_count} stars)</Text>
                <Text style={{fontSize: 13, color: 'black'}}>description: {item.description}</Text>
            </View>
        );
    }

最后就是數(shù)據(jù)請求了

    //rn的生命周期,初始化的時候會執(zhí)行
    componentDidMount() {
        //請求數(shù)據(jù)
        this.fetchData();
    }

    //返回當前顯示的view
    render() {
        //第一次加載等待的view
        if (!this.state.dataSource && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //請求失敗view
            return this.renderErrorView(this.state.errorInfo);
        }
        //加載數(shù)據(jù)

        return this.renderData();
    }

顯示結(jié)果


*最后奉上全部代碼

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ScrollView,
    ListView
} from 'react-native';

var REQUEST_URL = 'https://api.github.com/search/repositories?q=javascript&sort=stars';

class HelloWorld extends Component {
    //js組件的構(gòu)造函數(shù),js的生命周期
    constructor(props) {
        super(props);
        this.state = {
            //listView數(shù)據(jù)源
            dataSource: new ListView.DataSource({
                rowHasChanged: function (row1, row2) {
                    return row1 !== row2
                },
                sectionHeaderHasChanged:function (s1, s2) {
                    return s1 !== s2
                },
            }),
            //網(wǎng)絡請求狀態(tài)
            error: false,
            errorInfo: ""
        };
    }

    //rn的生命周期,初始化的時候會執(zhí)行
    componentDidMount() {
        //請求數(shù)據(jù)
        this.fetchData();
    }

    //返回當前顯示的view
    render() {
        //第一次加載等待的view
        if (!this.state.dataSource && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //請求失敗view
            return this.renderErrorView(this.state.errorInfo);
        }
        //加載數(shù)據(jù)

        return this.renderData();
    }

    //加載等待的view
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <Text>
                    Loading start...
                </Text>
            </View>
        );
    }

    //加載失敗view
    renderErrorView(error) {

        return (
            <View style={styles.container}>
                <Text>
                    Fail: {error}
                </Text>
            </View>
        );
    }

    //獲取到數(shù)據(jù)加載到控件上
    renderData() {
        return (
            <ScrollView style={
                {
                    paddingTop: 22,
                    paddingLeft: 5,
                    paddingBottom: 5,
                    paddingRight: 5
                }}>
                <Text style={{fontSize: 20}}>data:</Text>
                <ListView dataSource={this.state.dataSource}
                          renderRow={this.renderItemView}/>
            </ScrollView>
        );
    }

    //返回itemView
    renderItemView(item) {
        return (
            <View>
                <Text style={{fontSize: 15, color: 'blue'}}>name: {item.name} ({item.stargazers_count} stars)</Text>
                <Text style={{fontSize: 13, color: 'black'}}>description: {item.description}</Text>
            </View>
        );
    }

    fetchData() {
        //這個是js的訪問網(wǎng)絡的方法
        fetch(REQUEST_URL)
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({
                    //復制數(shù)據(jù)源
                    dataSource: this.state.dataSource.cloneWithRows(responseData.items)
                });
            })
            .catch((error) => {
                this.setState({
                    error: true,
                    errorInfo: error
                })
            })
            .done();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },

});


// 注意,這里用引號括起來的'HelloWorld'必須和你init創(chuàng)建的項目名一致
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容