You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用fetchNextPage后AnimatedFlatList跳转到列表顶部问题

AnimatedFlatList调用fetchNextPage后跳转到顶部的解决方案

常见原因及解决办法

  • 设置稳定的keyExtractor
    若FlatList未指定或使用不稳定的keyExtractor,数据更新时列表项会被重新渲染,导致滚动位置丢失。为每个列表项设置唯一且固定的标识:

    <AnimatedFlatList
      {...props}
      keyExtractor={(item) => item.id.toString()} // 替换为你的列表项唯一ID字段
      onScroll={onScroll({y}, {height}, {height: layoutH})}
      onEndReached={({distanceFromEnd}) => {
        if (distanceFromEnd < 0) {
          return;
        }
        if (hasNextPage && !isFetchingNextPage) {
          fetchNextPage();
        }
      }}
    />
    
  • 稳定useInfiniteQuery的查询Key
    如果request是对象类型,每次组件渲染可能生成新的对象引用,导致查询Key变化,触发初始数据重新获取,重置滚动位置。用useMemo缓存请求参数:

    import { useMemo } from 'react';
    
    // 替换[]内的内容为request对象的所有依赖项
    const memoizedRequest = useMemo(() => ({...request}), [/* request的依赖字段 */]);
    
    const {
      data,
      fetchNextPage,
      hasNextPage,
      isFetchingNextPage,
    } = useInfiniteQuery(
      [gate.getDiscover2.name, memoizedRequest],
      ({pageParam = 1}) =>
        gate.getDiscover2({...memoizedRequest, discover_page: pageParam}),
      {
        getNextPageParam: lastPage => {
          const {current_page, last_page} = lastPage.data || {};
          return current_page < last_page ? current_page + 1 : false;
        },
      },
    );
    
  • 启用maintainVisibleContentPosition
    通过FlatList的该属性强制保持当前可见内容的位置,避免数据更新时自动滚动到顶部:

    <AnimatedFlatList
      {...props}
      maintainVisibleContentPosition={{
        minIndexForVisible: 0,
        autoscrollToTopThreshold: 0,
      }}
      onScroll={onScroll({y}, {height}, {height: layoutH})}
      onEndReached={({distanceFromEnd}) => {
        if (distanceFromEnd < 0) {
          return;
        }
        if (hasNextPage && !isFetchingNextPage) {
          fetchNextPage();
        }
      }}
    />
    

内容的提问来源于stack exchange,提问作者Tohid Taghavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:41:29