首页 > 解决方案 > 滑动到列表末尾时不调用 FlatList `onEndReached` 回调

问题描述

FlatList组件有一个onEndReached属性。我正在实现一个简单的功能,当用户将屏幕滑动到列表末尾时,应用程序会发送一个新请求以从后端获取更多项目到列表中。以下是我尝试过的:

我首先创建了一个自定义组件MyCustomList,它只是FlatList. 有两个道具itemsgetMore

const MyCustomList = ({items, getMore}) => {
      ...
      return (
          <FlatList
            keyExtractor={keyExtractor}
            data={items}
            renderItem={renderItem}
            onEndReached={getMore}
            onEndReachedThreshold={0}
            ListFooterComponent={myFooter}
    />
  );
  ...
  export default MyCustomList;
}

在我的屏幕组件中,我使用上面的MyCustomList组件,如下所示:

import React, {useState} from 'react';
import MyCustomList from '../components/MyCustomList';
import {useQuery} from 'react-query';

const MyScreen = ({navigation}) => {

       const [page, setPage] = useState(1);

       // when screen is rendered, get the data from backend
       const {data, status} = useQuery('my-items', httpClient.fetchItems);

       // this is the function passed to MyCustomList component
       const getMoreItems = () => {
         // I expected to see this log every time when user swiped to the end of the list
         console.log('get next 10 items');
         setPage(page + 1);
      };

       return (
         <View>
            ...
            <MyCustomList items={data} getMore={getMoreItems} />
         </View>);
  };

如您所见,在我的屏幕组件中,我将getMoreItems函数传递给MyCustomList.

getMoreItems当我运行我的应用程序时,我只会在第一次显示屏幕时看到我放入函数中的日志消息一次。对我来说很奇怪,当时我还没有滑到列表的末尾。之后,每次我滑动到列表末尾时,getMoreItems都不会触发(我没有看到该日志消息)。这是为什么?

PS当滑动到列表底部时,我的屏幕现在没有重新渲染,因为getMoreItems没有触发setPage(page+1)没有调用。

标签: react-nativereact-native-flatlist

解决方案


推荐阅读