在加载列表中的200多个数据时,React本机应用程序崩溃

时间:2019-06-15 10:55:34

标签: react-native react-native-flatlist

我在flatlist中有无限滚动附带的数据列表。帖子数量超过200。当我在低端设备上运行该应用程序时,它崩溃了。

我尝试将props 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}/>}
            />

这是我的固定列表代码的样子

1 个答案:

答案 0 :(得分:0)

避免使用可能导致崩溃问题的根本原因的匿名函数,每次渲染项目时都会重新创建该函数。 提取所有匿名功能

此外,备忘录事件处理程序还将有助于最大程度地减少不必要的重新渲染,这会浪费您的内存。您可以使用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}
      />
    );
  }
}