react-native - 滑动到列表末尾时不调用 FlatList `onEndReached` 回调
问题描述
FlatList组件有一个onEndReached属性。我正在实现一个简单的功能,当用户将屏幕滑动到列表末尾时,应用程序会发送一个新请求以从后端获取更多项目到列表中。以下是我尝试过的:
我首先创建了一个自定义组件MyCustomList
,它只是FlatList
. 有两个道具items
和getMore
。
const MyCustomList = ({items, getMore}) => {
...
return (
<FlatList
keyExtractor={keyExtractor}
data={items}
renderItem={renderItem}
onEndReached={getMore}
onEndReachedThreshold={0}
ListFooterComponent={myFooter}
/>
);
...
export default MyCustomList;
}
items
是要在 上显示的数据FlatList
,getMore
是向后端发送请求以获取更多项目的功能。它应该在滑动到列表末尾时被调用。
在我的屏幕组件中,我使用上面的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)
没有调用。
解决方案
推荐阅读
- bootstrap-4 - Bootstrap5 轮播模板不工作(不响应)
- javascript - 为什么我在 React 中转换孩子时,键前有一个“.$”?
- postgresql - 连接到 sftp 文件夹,根据上次修改对文件进行排序,并将最新文件的内容转储到 RDS
- r - 使用 Cairo 导出为 SVG 时面板边框宽度不一致
- python - 如何将复数矩阵的索引相乘以获得新的复数矩阵
- bash - 使用制表符分隔文件中字段的空格分隔参数
- swift - 第三次返回视图时 ARView 崩溃
- python - 如何使用 python 和 scapy sniff() 和 send() 模拟以太网交换机
- c++ - 类似于 mp-units“向下转换工具”的类型的强别名,仅使用 C++14
- html - Bootstrap 5 列堆叠取决于宽度