react-native - 在 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}/>}
/>
这就是我的平面列表代码的样子
解决方案
避免可能是崩溃问题的根本原因的匿名函数,它会在每次呈现您的项目时重新创建。提取所有匿名函数。
此外,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}
/>
);
}
}
推荐阅读
- r - 使用 dplyr 包进行数据框转换的问题
- python - 在 SSH 服务器 VScode 上的 docker 容器中开发
- c# - 我想在 Redis 中存储 SignalR 连接 ID
- javascript - 材料设计列表元素到卡片的过渡
- php - 使用 axios 从 reactJS 将数据发送到 php 文件
- javascript - 基于另一个数组键和方向(左或右)的数组排序逻辑
- javascript - 运行 gulp 默认命令时发生 Gulp 错误
- json - 赛普拉斯:错误插入 json => 特殊字符序列:
- google-apps-script - setRichTextValue 到数组中的元素而不是一次一个单元格?
- json - Scala Play:列表到 Json-Array