首页 > 解决方案 > FlatList 渲染对于大数据集来说很重

问题描述

在我的应用程序中,我有一个FlatList包含 100 个项目的数据集。每个项目都有一个复杂的用户界面,我注意到它对性能造成了严重影响。包含列表的页面最多需要 5 秒才能加载。我注意到,在第一次渲染组件的那一刻,我的数据集中的每个项目也会调用该renderItem函数,我还注意到,如果该页面上的其他内容有任何其他 setState 更改,也会发生这种情况FlatList. 有没有办法防止重新渲染平面列表或至少重新渲染可见项目 - 就像在原生 Android 中使用 Recycle 一样?如何仅在组件首次出现时渲染可见项目?我尝试使用initialNumToRendermaxToRenderPerBatch但都没有奏效。

以下是代码示例:

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

const App = () => {

  const [text, setText] = React.useState('')

  const renderItem = ({ item }) => {
    console.log("Render Item")
    return (<Item title={item.title} />)
};

  return (
    <SafeAreaView style={styles.container}>

      <TextInput
        value={text}
        onChangeText={(val) => setText(val)}
      />

      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        initialNumToRender={6}
        maxToRenderPerBatch={6}
      />

    </SafeAreaView>
  );
}

如果我尝试在TextInput整个列表中输入某些内容会重新渲染,但列表中没有任何变化。我该如何防止这种情况发生?

标签: reactjsreact-nativereact-native-androidreact-native-flatlistreact-flatlist

解决方案


推荐阅读