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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容