React Native学习之路(5) -网络请求,ListVi

2017-07-13  本文已影响1134人  woow_wu7

Fetch,WebSocket,XMLHttpRequest

(1) fetch网络请求
 getMoviesFromApiAsync() {   //getMoviesFromApiAsync函数中使用fetch
    return fetch('url地址',{
                       method: 'POST',
                       headers: {
                       'Accept': 'application/json',
                      'Content-Type': 'application/json',
                        },
                   body: JSON.stringify({
                   firstParam: 'yourValue',
                   secondParam: 'yourOtherValue',
                         })
})
      .then((response) => response.json())
      .then((dataJson) => {
        return dataJson.key值;
      })
      .catch((error) => {
        console.error(error);
      });
  }
- 实例 - 

componentDidMount() {   //在加载完成时执行请求函数
    this._fetchData();
}
_fetchData() {
         fetch('http://image.baidu.com/channel/listjson?pn=0&rn=30&tag1=%E7%BE%8E%E5%A5%B3&tag2=%E5%85%A8%E9%83%A8&ie=utf8')
          .then( (response) => response.json() )
          .then( (dataJson) => {
                this.setState({ 
                    dataSource: this.state.dataSource.cloneWithRows(dataJson.data)
                });
           })
}
(2) mock.js来转换请求过来的json格式
(1)npm install mockjs --save
(2)在node_modules - mockjs - dist - mock.js然后找到dataImage删掉
(3)import Mock from 'mockjs';   (或者var Mock = require('mokjs');)
(4)Mock.mock('datajson'); 
(3) query-string参数字符串
(4) lodash

上拉加载:

(1)ListView- onEndReached :预加载

(2)ListView- onEndReachedThreshold: 距地底部多大时预加载

(3)ListView- renderFooter:在列表的底部增加一栏,后面跟要执行的函数(一般情况下用来显示加载的loading动画,俗称小菊花),这里有个大坑: 需要在后面加上.bind(this)

<listView 
    dataSource= { this.state.dataSource }
    renderRow= { this._renderRow.bind(this) }
    renderFooter = { this._renderFooter.bind(this) }  //_renderFooter()函数在下面第4点中有
    onEndReached = { this._onEndReached.bind(this) }
    onEndReachedThreshold = { 20 }
/>

(4)ActivityIndicator :显示一个圆形的loading提示符号。

 _renderFooter() {
        if(!this.hasMore()){    //如果没有更多数据,展示文案
            return (
                <View>
                    <Text>没有更多数据</Text>
                </View>
            )
        }
        else return <ActivityIndicator
                style={[styles.centering, {height: 80}]}
                size="large"
                color="#ee735c"
            />
    }

(5) showsVerticalScrollIndicator:隐藏ListView的纵向滚动条;

showsVerticalScrollIndicator= { false }   
arrayObject.slice(start,end)
start必须,规定从何处开始选取;
end可选,规定从何处结束选取;

下拉刷新:

(1) RefreshControl :下拉刷新组件

<listView 
    dataSource= { this.state.dataSource }
    renderRow= { this._renderRow.bind(this) }
    renderFooter = { this._renderFooter.bind(this) }  //_renderFooter()函数在下面第4点中有
    onEndReached = { this._onEndReached.bind(this) }
    onEndReachedThreshold = { 20 }
    refreshControl= {
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh}
                            tintColor="#ff0000"
                            title="Loading..."
                            titleColor="#00ff00"
                            colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#ffff00"
                        />
                    }
/>

效果图:


20170713132259.gif 2.png

完整代码:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    Image,
    ListView,
    TouchableOpacity,
    Dimensions,
    ActivityIndicator,
    RefreshControl
}from 'react-native';

// var MOCK = require('mockjs');

// import Request from '../common/request';



// var cachedResults = {
//     nextPage =
// }

var width = Dimensions.get('window').width;
// var height = Dimensions.get('window').height;

// var cachedResults = {
//     nextPage: 1,   //下一页
//     items: [ ],     // 缓存的数据列表
//     total: 0       //所有的列表的总长度
//
// };

let ip = [];
let page = 1;
export default class List extends Component {
    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows([ {
                "id": "710000201512201032",
                "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
            },
                {
                    "id": "540000201705130953",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "36000020090726779X",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "23000019890819858X",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "810000199101084138",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "810000198412233773",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "610000200610314331",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                },
                {
                    "id": "360000201607162472",
                    "image_url": "http://g1.ykimg.com/050C0000595C3945ADC0AEC7BF085F58",
                    "video": "http://www.imooc.com/static/lib/mocoplayer/2.5.1/mocoplayer.swf?v=2.4.3"
                }
            ]),
            isLoadingTail: false,
            isRefreshing: false
        };
    }
    //ListView的renderRow方法
    _renderRow(rowData, sectionID, rowID) {

        return (
            <TouchableOpacity>
                <View>
                    <View style={ styles.titleContainer}>
                        <Text style={styles.title}>美女和男神的养成密集,让赵丽颖来告诉你</Text>
                    </View>

                    <View>
                        <Image source={{ uri: rowData.image_url }} style={styles.img}></Image>
                        <Image source={ require('../../go.png') } style={styles.go}></Image>
                    </View>

                    <View style={styles.bottom}>
                        <View style={styles.bottomBoth}>
                            <Image style={styles.sLogo} source={ require('../../love.png') }></Image>
                            <Text style={ styles.bottomText}>喜欢</Text>
                        </View>
                        <View style={styles.bottomBoth}>
                            <Image style={styles.sLogo2} source={ require('../../discuss.png') }></Image>
                            <Text style={ styles.bottomText}>评论</Text>
                        </View>
                    </View>

                </View>

            </TouchableOpacity>
        );
    }

    // componentDidMount() {
    //     this._fetchData(1);
    // }

    // _fetchData() {
    //
    // }
    // // 调用fetchData
    // componentDidMount() {
    //     this._fetchData();
    // }

    // fetch网络请求
    // _fetchData() {
    //     return(
    //         request.get(config.api.base + config.api.creations , { accessToken: '111112223' })
    //             .then((response) => response.json())
    //             .then((response) => {
    //                 // var data = MOCK.mock(response);
    //                 // console.log(data);
    //
    //                 console.log(response);
    //             })
    //             .catch((error) => {
    //                 console.error(error);
    //             })
    //     );
    // }
    // _hasMore() {
    //     return  cachedResults.items.length !== cachedResults.total;
    // }
    componentDidMount() {
        this.getData(1,3)
    }

    getData(page,rn) {
        this.setState({
            isLoadingTail: true
        });
        let newUrl = 'http://image.baidu.com/channel/listjson?pn='+ page + '&rn='+ rn +'&tag1=%E7%BE%8E%E5%A5%B3&tag2=%E5%85%A8%E9%83%A8&ie=utf8';
            fetch(newUrl)
                .then( (response) => response.json())
                .then( (dataJson) => {
                    ip = dataJson.data;
                    this.setState({
                        isLoadingTail: false,
                        dataSource: this.state.dataSource.cloneWithRows(dataJson.data)
                    });
                })
                .catch( (error) => {
                    console.error(error);
                })
    }
    hasMore() {
        return ip != 100;
    }
    onEndReached() {
        if( !this.hasMore() || this.state.isLoadingTail){
            return
        }
        var that = this;
        page = page+20;
        var rn =5;
            fetch('http://image.baidu.com/channel/listjson?pn='+ page + '&rn='+ rn +'&tag1=%E7%BE%8E%E5%A5%B3&tag2=%E5%85%A8%E9%83%A8&ie=utf8')
                .then( (response) => response.json())
                .then( (dataJson) => {
                    ip = ip.slice().concat(dataJson.data);
                    setTimeout(function(){
                        that.setState({
                            dataSource: that.state.dataSource.cloneWithRows(ip)
                        })
                    },2000);

                })
                .catch( (error) => {
                    console.error(error);
                })
    }
    _renderFooter() {
        if(!this.hasMore()){
            return (
                <View>
                    <Text>没有更多数据</Text>
                </View>
            )
        }
        else return <ActivityIndicator
                style={[styles.centering, {height: 80}]}
                size="large"
                color="#ee735c"
            />
    }

    _onRefresh() {
        if(!this.hasMore() || this.state.isRefreshing){
            return
        }
        this.setState({
            isRefreshing: false
        });
        page= page+20;
        var rn = 4;
        fetch('http://image.baidu.com/channel/listjson?pn='+ page + '&rn='+ rn +'&tag1=%E7%BE%8E%E5%A5%B3&tag2=%E5%85%A8%E9%83%A8&ie=utf8')
            .then( (response) => response.json())
            .then( (dataJson) => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(dataJson.data)
                })
            })
    }
    render() {
        return (
            <View style={styles.content}>
                <View style={ styles.header}>
                    <Text style={styles.headerTitle}>
                        列表页
                    </Text>
                </View>

                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={ this._renderRow.bind(this) }
                    renderFooter={ this._renderFooter.bind(this)}
                    onEndReached={ this.onEndReached.bind(this)}
                    onEndReachedThreshold = { 100 }
                    enableEmptySections = { true }
                    automaticallyAdjustContentInserts = { false }
                    showsVerticalScrollIndicator = { false }
                    refreshControl= {
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            tintColor="#ff0000"
                            title="Loading..."
                            titleColor="#00ff00"
                            colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#fff"
                        />
                    }
                />

            </View>
        )
    }
}


const styles = StyleSheet.create({
    content: {
        flex:1,
        // justifyContent: 'center',
        // alignItems: 'center'
    },
    header: {
        backgroundColor: '#ee735c',
        paddingTop:16,
        paddingBottom:16
    },
    headerTitle: {
        color:'white',
        fontWeight: '600',
        textAlign: 'center',
        fontSize: 18,
        letterSpacing: 300,
    },
    img: {
        width: width,
        height: 300
    },
    go: {
        position: 'absolute',
        width: 50,
        height: 50,
        bottom: 30,
        right:60
    },
    title: {
        fontSize: 20,
        letterSpacing: 18
    },
    titleContainer: {
        height:46,
        marginTop:14
    },
    bottom: {
        height:60,
        paddingBottom:84,
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor:"#eee"
    },
    bottomBoth: {
        flexDirection: 'row',
        justifyContent: 'center',
        width: width / 2 - 0.5,
        backgroundColor:"white",
        height:70,
        paddingTop: 4,
        alignItems: 'center'
    },
    sLogo: {
        width: 38,
        height:38,
        marginRight: 8
    },
    sLogo2: {
        width: 42,
        height:44,
        marginRight: 8
    },
    bottomText: {
        fontSize: 20
    },
    centering: {
        flexDirection: 'row',
        justifyContent: 'center'
    }
});
上一篇下一篇

猜你喜欢

热点阅读