【发布时间】:2019-05-16 16:52:42
【问题描述】:
由于某种原因,当在 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-native optimization scroll react-native-flatlist