React Native实现列表刷新

React Native中的ListView

React Native 提供了几个适用于展示长列表数据的组件,一般而言我们会选用FlatList或是SectionList

FlatList

FlatList组件用于显示一个垂直的滚动列表,其中的元素之间结构近似而仅数据不同。 FlatList更适于长列表数据,且元素个数可以增删。和ScrollView不同的是,FlatList并不立即渲染所有元素,而是优先渲染屏幕上可见的元素。
FlatList组件必须的两个属性是datarenderItemdata是列表的数据源,而renderItem则从数据源中逐个解析数据,然后返回一个设定好格式的组件来渲染。

import React, {Component} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';


type Props = {};

class Home extends Component<Props> {

    render() {
        return (
            <View style={styles.container}>
                <FlatList data={[{key: 'Devin'},
                    {key: 'Jackson'},
                    {key: 'James'},
                    {key: 'Joel'},
                    {key: 'John'},
                    {key: 'Jillian'},
                    {key: 'Jimmy'},
                    {key: 'Julie'}]}
                          renderItem={({item}) => <Text style={styles.welcome}>{item.key}</Text>}></FlatList>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    }
});

// 输出组件类
module.exports = Home;
SectionList

如果要渲染的是一组需要分组的数据,也许还带有分组标签的,那么SectionList将是个不错的选择,就有点像Android中的ExpandListView:

import React, {Component} from 'react';
import {SectionList, StyleSheet, Text, View} from 'react-native';


type Props = {};
class Shop extends Component<Props> {

    render() {
        return (
            <View style={styles.container}>
                <SectionList
                    sections={[
                        {title: 'D', data: ['Devin']},
                        {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
                    ]}
                    renderItem={({item})=> <Text style={styles.item}>{item}</Text>}
                    renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
                    keyExtractor={(item, index) => index}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    sectionHeader: {
        paddingTop: 2,
        paddingLeft: 10,
        paddingRight: 10,
        paddingBottom: 2,
        fontSize: 14,
        fontWeight: 'bold',
        backgroundColor: 'rgba(247,247,247,1.0)',
    },
    item: {
        padding: 10,
        fontSize: 18,
        height: 44,
    },
});

// 输出组件类
module.exports = Shop;

服务器数据绑定到FlatList

React Native 提供了和 web 标准一致的Fetch API,用于满足开发者访问网络的需求。下面我们用Fetch 来请求网络,然后用ListView显示:

import React, {Component} from 'react';
import {StyleSheet, Text, View,FlatList} from 'react-native';


type Props = {};
class Mine extends Component<Props> {

    constructor(props){
        super(props);

        this.state = {
            data: null,
        };
    }

    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={this.renderItemView}
                />
            </View>
        );
    }

    //返回itemView,item参数内部会传入进去
    renderItemView({item}) {
        return (
            <View>
                <Text  style={styles.content}>标题: {item.title}</Text>
            </View>
        );
    }

    // 为啥把fetch写在componentDidMount()中呢,因为这是一个RN中组件的生命周期回调函数,会在组件渲染后回调
    componentDidMount(){
        fetch('http://183.131.205.41/Bbs')
            .then((response)=> response.json()) // 将response转成json传到下一个then中
            .then((jsonData2)=> {
                this.setState({
                    data:jsonData2.data, // 返回json的data数组
                });
                alert("code:" + jsonData2.code);// 弹出返回json中的code
            })
            .catch((error) => {          //注意尾部添加异常回调
            alert(error);
        });
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    }
});

// 输出组件类
module.exports = Mine;

下拉刷新与加载更多

FlatList性质也是一样的只不过使用起来更加封闭、内部封装好了 添加头尾布局、下拉刷新、上拉加载等功能… 实现的效果:

import React, {Component} from 'react';
import {
    ActivityIndicator,
    FlatList,
    RefreshControl,
    StyleSheet,
    Text,
    TouchableNativeFeedback, TouchableOpacity,
    View
} from 'react-native';

let totalPage = 5;//总的页数
let itemNo = 0;//item的个数
type Props = {};
const REQUEST_URL = 'http://183.131.205.41/Bbs?page=';

class More extends Component<Props> {

    constructor(props) {
        super(props)
        this.state = {
            page: 1,
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: '',
            dataArray: [],
            showFoot: 0, // 控制foot, 0:隐藏footer  1:已加载完成,没有更多数据   2 :显示加载中
            isRefreshing: false,//下拉控制
        }
    }

    //网络请求——获取数据
    fetchData() {
        //这个是js的访问网络的方法
        console.log(REQUEST_URL + this.state.page)
        fetch(REQUEST_URL + this.state.page, {
            method: 'GET',
        })
            .then((response) => response.json())
            .then((responseData) => {
                let data = responseData.data;//获取json 数据并存在data数组中
                let dataBlob = [];//这是创建该数组,目的放存在key值的数据,就不会报黄灯了
                let i = itemNo;
                //将data循环遍历赋值给dataBlob
                data.map(function (item) {
                    dataBlob.push({
                        key: i,
                        title: item.title,
                        createtime: item.createtime
                    })
                    i++;
                });
                itemNo = i;
                let foot = 0;
                if (this.state.page >= totalPage) {
                    foot = 1;//listView底部显示没有更多数据了
                }
                this.setState({
                    //复制数据源
                    dataArray: this.state.dataArray.concat(dataBlob),
                    isLoading: false,
                    showFoot: foot,
                    isRefreshing: false,
                });

                data = null;//重置为空
                dataBlob = null;
            })
            .catch((error) => {
                alert(error);
                this.setState({
                    error: true,
                    errorInfo: error
                })
            })
            .done();
    }

    componentDidMount() {
        this.fetchData();
    }

    // (true 的话进行下2步操作componentWillUpdate和componentDidUpdate
    shouldComponentUpdate() {
        return true
    }

    handleRefresh = () => {
        this.setState({
            page: 1,
            isRefreshing: true,//tag,下拉刷新中,加载完全,就设置成flase
            dataArray: []
        });
        this.fetchData()
    }

    //加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    // 给list设置的key,遍历item。这样就不会报黄线
    _keyExtractor = (item, index) => index.toString();

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

    //返回itemView
    _renderItemView({item}) {
        //onPress={gotoDetails()}
        const gotoDetails = () => Actions.news({'url': item.url})//跳转并传值
        return (
            // <TouchableNativeFeedback onPress={() => {Actions.news({'url':item.url})}} >////切记不能带()不能写成gotoDetails()
            <TouchableNativeFeedback onPress={gotoDetails}>
                <View>
                    <Text style={styles.title}>标题:{item.title}</Text>
                    <Text  style={styles.content}>时间: {item.createtime}</Text>
                </View>
            </TouchableNativeFeedback>
        );
    }

    renderData() {
        return (
            <FlatList
                data={this.state.dataArray}
                renderItem={this._renderItemView}
                ListFooterComponent={this._renderFooter.bind(this)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={1}
                ItemSeparatorComponent={this._separator}
                keyExtractor={this._keyExtractor}
                //为刷新设置颜色
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
                        colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                        progressBackgroundColor="#ffffff"
                    />
                }
            />

        );
    }

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _separator() {
        return <View style={{height: 1, backgroundColor: '#999999'}}/>;
    }

    _renderFooter() {
        if (this.state.showFoot === 1) {
            return (
                <View style={{height: 30, alignItems: 'center', justifyContent: 'flex-start',}}>
                    <Text style={{color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator/>
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了,则返回
        if (this.state.showFoot != 0) {
            return;
        }
        //如果当前页大于或等于总页数,那就是到最后一页了,返回
        if ((this.state.page != 1) && (this.state.page >= totalPage)) {
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot: 2});
        //获取数据,在componentDidMount()已经请求过数据了
        if (this.state.page > 1) {
            this.fetchData();
        }
    }

}

const styles = StyleSheet.create({
    container: {
        padding: 10,
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    title: {
        marginTop: 8,
        marginLeft: 8,
        marginRight: 8,
        fontSize: 15,
        color: '#ffa700',
    },
    footer: {
        flexDirection: 'row',
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 10,
    },
    content: {
        marginBottom: 8,
        marginLeft: 8,
        marginRight: 8,
        fontSize: 14,
        color: 'black',
    }

});

// 输出组件类
module.exports = More;
图片.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容