首页 > 解决方案 > 在 flatlist 中加载 200 多个数据时,React 本机应用程序崩溃

问题描述

我在平面列表中有无限滚动的数据列表。帖子数为200+。当我在低端设备上运行应用程序时,它会崩溃。

我尝试将道具 removeClippedSubviews 添加为 true 但这并没有太大帮助。

我还检查了后台应用程序使用的内存。它不断增加。如何管理这个内存?

          <FlatList
            removeClippedSubviews={true}
            maxToRenderPerBatch={15}
            initialNumToRender={5}
            refreshing={this.state.refresh}
            bounces={false}
            onRefresh={()=>this.refreshAllTweets()}
            data={tweets}
            ref={(c) => {this.flatList = c;}}
            keyExtractor={(item, index) => index.toString()}
            onEndReached={()=>this.endReached()}
            onEndReachedThreshold={0.1}
            renderItem={({item}) => <TweetItem reloadComponent={()=>this.reload()} name={this.state.name}  onPress={()=>this.goToDetail(item.id)} onImagePress={()=>this.toggleModal(item.id)} onCommentPress={()=>this.showComments(item.id)} tweet={item}/>}
            />

这就是我的平面列表代码的样子

标签: react-nativereact-native-flatlist

解决方案


避免可能是崩溃问题的根本原因的匿名函数,它会在每次呈现您的项目时重新创建。提取所有匿名函数

此外,memoize 事件处理程序还有助于最大限度地减少不必要的重新渲染,这会使您的内存膨胀。您可以使用 lodash 库来实现这一点。

yarn add lodash

这是呈现 FlatList 的高效方式。

import { memoize, curry } from "lodash/fp";

class YourComponent {
  assignRef = (c) => {
    this.flatList = c;
  }

  onTweetPress = memoize(curry((id, _ev) => {
    this.goToDetail(item.id)
  }));

  onImagePress = memoize(curry((id, _ev) => {
    this.toggleModal(id)
  }));

  onImagePress = memoize(curry((id, _ev) => {
    this.toggleModal(id)
  }));

  onCommentPress = memoize(curry((id, _ev) => {
    this.showComments(id)
  }));

  renderItem = ({ item }) => (
    <TweetItem
      reloadComponent={this.reload}
      name={this.state.name}
      onPress={this.onTweetPress(item.id)}
      onImagePress={this.onImagePress(item.id)}
      onCommentPress={this.onCommentPress(item.id)}
      tweet={item}
    />
  )

  keyExtractor = (item, index) => (index.toString())

  render() {
      return (
      <FlatList
        removeClippedSubviews={true}
        maxToRenderPerBatch={15}
        initialNumToRender={5}
        refreshing={this.state.refresh}
        bounces={false}
        onRefresh={this.refreshAllTweets}
        data={tweets}
        ref={this.assignRef}
        keyExtractor={this.keyExtractor}
        onEndReached={this.endReached}
        onEndReachedThreshold={0.1}
        renderItem={this.renderItem}
      />
    );
  }
}

推荐阅读