首页 > 解决方案 > 滚动时内存使用量激增(React Native FlatList)

问题描述

出于某种原因,当在 React Native 中使用 FlatList 时,我的 iOS 模拟器在滚动列表时开始突突,显示滚动时 CPU 使用率增加了约 20%。这会导致速度较慢的设备出现问题,包括 Android 和 iOS(尤其是 Android)。

我尝试了一些优化技巧,没有太大的变化。我添加了一个 shouldComponentUpdate 函数,它为列表中的每个组件返回 false。我已经删除了对在 render() 中作为 props 传递的函数的任何调用,并且我首先切换到使用 FlatList(以前它只是呈现组件的数组的 .map)。

我使用 FlatList 的组件的 render()

    <View style={{ flexDirection: 'row', flexWrap: 'wrap', backgroundColor: 'white' }}>
        <FlatList
          style={{ flexDirection: 'row', flexWrap: 'wrap', backgroundColor: 'white' }}
          data={this.props.items}
          numColumns={2}
          windowSize={3}
          renderItem={({ item }) => (<ItemListRow
            goToItemOverride={this.goToItemOverride}
            item={item}
            navigator={this.props.navigator}
            category={this.props.category}
          />)}
        />
      </View>

renderItem 组件的 render()

    <Card
        style={this.styles.itemCard}
      >
        <View style={{ paddingTop: 0, paddingBottom: 0 }}>
          <View style={{ alignItems: 'center' }}>
            <TouchableOpacity style={{ height: 275 }} onPress={() => this.goToItemDetails(this.props.item)}>
              {this.state.loading ? <View style={{ position: 'absolute', left: 0, top: 0 }} >{this.defaultImage()}</View> : null }
              {this.image(this.styles.categoryimg, this.props.item.image.src)}
            </TouchableOpacity>
          </View>
        </View>
        <View>
          <View style={{ textAlign: 'center' }}>
            <Text style={{ textAlign: 'center', fontSize: 18 }} numberOfLines={3}>{this.props.item.title}</Text>
            {
              (this.props.item.compare_at_price) ?
                <View style={{ height: 20, alignItems: 'flex-end', flexDirection: 'row' }}>
                  <Text style={this.styles.itemPrice}>
                    ${this.props.item.price}
                  </Text>
                  <Text style={this.styles.strikethrough}>
                    ${this.props.item.compare_at_price}
                  </Text>
                </View>
                :
                <Text style={this.styles.itemPrice}>${this.props.item.price}</Text>
            }
          </View>
        </View>
      </Card>

我觉得这是一个非常简单的列表,所有事情都考虑在内,所以我不确定减速可能发生在哪里。我尝试从列表元素中删除图像(认为图像可能太大),但没有明显差异。此列表中的最大商品数量约为 30,因此我并不是要在此处呈现整个商店的商品价值。

任何意见,将不胜感激。

标签: react-nativeoptimizationscrollreact-native-flatlist

解决方案


我的性能也有问题FlatList。我尝试了所有能找到的修复方法,但最终我放弃并改用recyclerlistview. 它使用起来更复杂,并且每个项目都需要一个静态高度,但为了性能提升,这是值得的。

如果你不使用Expo,你也可以试试react-native-largelist


推荐阅读