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

如何在FlatList数据每次发生变更时显示活动指示器?

解决方案

1. 实现逻辑说明

通过新增加载状态控制指示器显隐,在用户切换分组时先开启加载状态,再更新数据源;利用FlatList原生的渲染完成回调关闭加载,保证指示器消失时列表已经完成新数据渲染。

2. 完整代码示例

import { ActivityIndicator, View, FlatList, StyleSheet } from 'react-native';

// 组件内部逻辑
const [isLoading, setIsLoading] = useState(false);
const [selectedStream, setSelectedStream] = useState([]);
const feedRef = useRef(null);

// 切换分组的触发函数,替换你原有的分组切换逻辑即可
const handleGroupSwitch = (newStreamData) => {
  setIsLoading(true);
  setSelectedStream(newStreamData);
}

// 空数据兜底:如果切换后数据源为空直接关闭加载
useEffect(() => {
  if(selectedStream.length === 0) setIsLoading(false);
}, [selectedStream])

// 渲染部分
return (
  <View style={styles.container}>
    <FlatList   
      maxToRenderPerBatch={5}
      bounces={false}
      windowSize={5}
      ref={feedRef}   
      data={selectedStream}
      // 列表内容尺寸变化时触发,代表新数据已完成渲染
      onContentSizeChange={() => setIsLoading(false)}
      // 保留你原有的renderItem逻辑即可
      renderItem={({item}) => <YourCustomListItem item={item} />}
    /> 
    {/* 加载指示器,加载时居中覆盖在列表上层 */}
    {isLoading && (
      <View style={styles.loadingOverlay}>
        <ActivityIndicator size="large" color="#2196F3" />
      </View>
    )}
  </View>
)

// 样式定义
const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative'
  },
  loadingOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    // 半透明遮罩可自行调整或删除
    backgroundColor: 'rgba(255,255,255,0.7)',
  }
})

3. 可选优化项

  • 如果遇到加载指示器提前消失的问题,可以给关闭加载的逻辑加100ms以内的延时兜底:
    onContentSizeChange={() => setTimeout(() => setIsLoading(false), 80)}
    
  • 不需要半透明遮罩直接删除loadingOverlay的backgroundColor属性即可
  • 如果需要等全量数据渲染完成再关闭加载,可临时将maxToRenderPerBatch设置为selectedStream.length,仅适合数据量较小的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:15:00