onEndReached FlatList React Native [英] onEndReached FlatList React Native

查看:39
本文介绍了onEndReached FlatList React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在我的 React Native 项目中有一个 FlatList,用于渲染来自 nodejs 后端的帖子.我已将分页应用到我的后端,当我在邮递员上测试它时它正在工作.我的问题是当我在模拟器上测试我的应用程序时,当我到达页面 0 的末尾时,页面 1 没有加载.

i currently have a FlatList in my React Native project that renders the posts from nodejs backend. I have applied the pagination to my backend and it is working when i am testing it on postman. My problem is when i test my app on a simulator when i reach the end of the page 0, page 1 does not load.

这是我的 FlatList:

Here is my FlatList:

 <FlatList
      data={posts} // to have all the data
      keyExtractor={(post) => post.id.toString()}
      renderItem={({ item }) => (
        <PostCard
          title={item.title}
          subTitle={item.subTitle}
        />
      )}
       onEndReached={onScrollHandler}
       onEndThreshold={0}
    />

 const { data: posts, error, loading, request: loadPosts } = useApi(
postsApi.getPosts
  );

 useEffect(() => {
loadPosts();
  }, []);

  const[page,setPage]=useState(0);
  const[profiles,setProfiles]=useState([]);

  const fetchRecords=(page)=>{
  const newRecords = []
  for(var i = page * 10, il = i + 10; i < il && i < posts.length; i++){
  newRecords.push(posts[i]);
  }
  setProfiles(...profiles, ...newRecords)
  }

 const onScrollHandler =()=>{
 setPage(page+1);
 fetchRecords(page)
 }

这是我的 nodeJS 后端:

Here is my nodeJS backend:

  router.get("/",
  async (req, res) => {
  const getPagination = (page, size) => {
const limit = size ? +size : 10;
const offset = page ? page * limit : 0;

 return { limit, offset };
 };

const { page, size } = req.query;
 const { limit, offset } = getPagination(page, size);

 const posts = await Post.findAll({
 limit,offset,

这里我的路由是/posts,我在后端的 index.js 中声明.

Here my route is /posts which i declared in my index.js in my backend.

在后端应用分页之前,当我过去在前端执行 console.log(posts) 时,我曾经获取所有帖子,但是在执行 console.log(posts) 时应用分页后,我只获取了以下内容的帖子第一页.

Before applying pagination in my backend, when i used to do console.log(posts) in frontend i used to get all my posts but after i applied pagination when i do console.log(posts) i only get the posts for the first page.

推荐答案

您是否检查了在到达平面列表末尾时是否调用了 onScrollHandler 函数.

Did you inspect if your onScrollHandler function is called whenever you reached at the end of the flat list.

另外,请将您的平面列表包装在 SafeAreaView 中,并赋予 SafeAreaView 样式的 flex : 1

Also please wrap your flat list inside SafeAreaView and give SafeAreaView style of flex : 1

<SafeAreaView>
<FlatList/>
</SafeAreaView>

这篇关于onEndReached FlatList React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆