flatlist тянуть, чтобы refre sh реагировать - PullRequest
0 голосов
/ 20 апреля 2020

Я использовал приведенный ниже пример и реализовал плоский список и ленивую загрузку. Но когда я пытаюсь изменить sh, мне нужно добавить счетчик, но проблема в том, что мой контроль не идет внутрь handleRefesh. Я событие поставил консоль, но консоль не печатает. Можете ли вы сказать мне, как это исправить. Ниже приведен фрагмент кода.

https://scotch.io/tutorials/implementing-an-infinite-scroll-list-in-react-native

import * as React from 'react';
import { ActivityIndicator, FlatList, Animated, Dimensions, LayoutAnimation, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";
//import ComingSoon from '../core/components/common/ComingSoon';
//import { COLORS } from '../core/constants/Colors';
//import { ScreenContainer } from '../core/layout/ScreenContainer';
import { Table, TableWrapper, Row } from 'react-native-table-component';

import CheckBox from 'react-native-check-box';
import axios from 'axios';




import {
    LazyloadScrollView,
    LazyloadView,
    LazyloadImage
} from 'react-native-lazyload';

import data from './MOCK_DATA.json';


export default function OrderDetails() {
    // screen height and width
    const { width, height } = Dimensions.get('window');

    const [tableHead, setTableHead] = React.useState(['Head', 'Head2', 'Head3', 'Head4', 'Head5', 'Head6', 'Head7', 'Head8', 'Head9']);

    const [widthArr, setWidthArr] = React.useState(['40, 60, 80, 100, 120, 140, 160, 180, 200']);

    const [flatListData, setFlatListData] = React.useState([]);
    const [totalFlatListData, setTotalFlatListData] = React.useState([]);

    const [page, setpage] = React.useState(1);
    const [loading, setloading] = React.useState(true);

    const [loadingMore, setLoadingMore] = React.useState(false);
    const [filtering, setFiltering] = React.useState(false);


    const [refreshing, setRefreshing] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [isChecked, setIsChecked] = React.useState(false);



    console.log("Table ---->", Table);

    let start = ~~(Math.random() * 900);
    let list = data.splice(start, 100);

    React.useEffect(() => {
        loadLazyLoadingAPI();
    }, []);


    const loadLazyLoadingAPI = () => {
        let headers: any = {};
        if (page <= 5) {

            headers['Content-Type'] = 'application/json';

            axios.get(`https://api.punkapi.com/v2/beers?page=${page}&per_page=10`,

                {
                    headers: headers
                }


            )
                .then(response => {
                    console.log("lazyload", response);
                    let data: any[] = flatListData;

                    setFlatListData([...data, ...response.data]);
                    setTotalFlatListData([...totalFlatListData, ...response.data]);

                    setloading(false);
                    setLoadingMore(false);
                    setRefreshing(false);



                })

                .catch(error => {
                    console.log(error);
                    setloading(false);
                })
        }
        // }
    }

    const handleRefesh = () => {
        console.log('handle Refresh -->')
        setpage(1);
        setRefreshing(true);

    }

    const hadndleLoadingMore = () => {
        console.log('handle loading more -->')
        setpage(page + 1);
        setLoadingMore(true);

    }


    const renderFooter = () => {
        if (loadingMore) return null;

        return (
            <View
                style={{
                    position: 'relative',
                    width: width,
                    height: height,
                    paddingVertical: 20,
                    borderTopWidth: 1,
                    marginTop: 10,
                    marginBottom: 10,
                    //borderColor: colors.veryLightPink
                }}
            >
                <ActivityIndicator animating size="large" />
            </View>
        );
    };



    React.useEffect(() => {
        if (loading || loadingMore) {
            loadLazyLoadingAPI();
        }
    }, [loading, loadingMore, page]);


    if (loading) {
        console.log('handle ActivityIndicator -->')

        return (<View>
            <Text style={{ alignSelf: 'center' }}>Loading beers</Text>
            <ActivityIndicator />
        </View>)
    }

    return (
        <View style={styles.container}>

            {/* <ScrollView
      refreshControl={ 
      <RefreshControl 
      refreshing={this.state.isFetching} 
      onRefresh={this.handleRefresh} 
      /> 
      } 
 > */}




            <CheckBox
                style={{ flex: 1, padding: 10 }}
                onClick={(e: any) => {
                    if (!isChecked) {
                        setFlatListData(totalFlatListData.filter((item: any) => {
                            return item.id % 2 === 0;
                        }));
                    } else {
                        setFlatListData(totalFlatListData);
                    }
                    setIsChecked(!isChecked);
                }}
                isChecked={isChecked}
                leftText={"odd"}
            />

            <CheckBox
                style={{ flex: 1, padding: 10 }}
                onClick={(e: any) => {
                    if (!isChecked) {
                        setFlatListData(totalFlatListData.filter((item: any) => {
                            return item.id % 2 != 0;
                        }));
                    } else {
                        setFlatListData(totalFlatListData);
                    }
                    setIsChecked(!isChecked);
                }}
                isChecked={isChecked}
                leftText={"even"}
            />

            {/* <LazyloadScrollView
       style={styles.container}
       contentContainerStyle={styles.content}
        //name="scrollExample"
    >

</LazyloadScrollView> */}


            <FlatList
                contentContainerStyle={{
                    flex: 1,
                    flexDirection: 'column',
                    height: '100%',
                    width: '100%'
                }}
                data={flatListData}
                keyExtractor={(item: any) => item.id.toString()}

                renderItem={({ item }) => (
                    <View
                        style={{
                            marginTop: 25,
                            width: '50%'
                        }}
                    >
                        <Text>{item.name}</Text>
                    </View>
                )}
                onRefresh={handleRefesh}
                refreshing={refreshing}
                onEndReached={hadndleLoadingMore}
                ListFooterComponent={renderFooter}

                onEndReachedThreshold={0.5}
                initialNumToRender={10}





            />

            {/* </ScrollView> */}

        </View>






    );
}



const styles = StyleSheet.create({







    container: {
        flex: 1,
        backgroundColor: '#F5FCFF'
    },
    content: {
        paddingTop: 20,
        justifyContent: 'center',
        alignItems: 'center'
    },
    view: {
        height: 70,
        width: 320,
        paddingVertical: 5,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#666'
    },
    file: {
        width: 320,
        flex: 1,
        flexDirection: 'row'
    },
    id: {
        width: 50,
        alignItems: 'center',
        justifyContent: 'center'
    },
    idText: {
        fontSize: 10
    },
    detail: {
        justifyContent: 'space-around',
        flex: 1
    },
    name: {
        textAlign: 'center',
        lineHeight: 15,
        color: '#666',
        marginBottom: 5
    },
    email: {
        fontSize: 10,
        color: 'blue',
        textDecorationColor: 'blue',
        textDecorationLine: 'underline',
        textDecorationStyle: 'solid'
    },
    ip: {
        fontSize: 12,
        color: 'grey'
    },
    gender: {
        width: 50,
        alignItems: 'center',
        justifyContent: 'center'
    },
    genderText: {
        fontSize: 10
    },
    title: {
        color: '#333',
        fontSize: 12
    },
    male: {
        color: 'skyblue'
    },
    female: {
        color: 'pink'
    }




});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...