【发布时间】:2019-04-01 05:48:02
【问题描述】:
经过一些研究,我似乎需要使用 PureComponent 而不是常规组件来提高我的 FlatList 的速度。这样它就不会重新渲染整个列表,只会重新渲染被更改的行。但是,当我这样做时,平面列表不会重新呈现。
这个问题How to re-render flatlist? 和其他类似的问题表明我必须在我的FlatList 中使用extradata={this.state},以便它可以查看数据源中是否发生了任何数据更改但它不起作用
我尝试过 this.state、this.state.symbols,尝试使用布尔值并在我的 onPress 函数中强制更改它,但似乎没有任何效果。
我将列表项从渲染函数中移到外部 js 文件中的自己的类中
export default class MyListItem extends React.PureComponent {
render() {
const { item } = this.props;
return (
<View style={{flex: 1, flexDirection: 'row'}}>
<View style={{backgroundColor: 'powderblue'}}>
<Ionicons style={styles.listItemIcon} name={item.iconName} />
</View>
<View style={{backgroundColor: 'skyblue'}}>
<Text style={styles.listItem}>
{item.coinName.toUpperCase()} {item.symbol}
</Text>
</View>
</View>
);
};
}
我的 renderListItem 函数现在看起来像这样
renderListItem = ({ item , index}) => {
return(
<TouchableOpacity
onPress={() => this.onPressListItem(index)}
>
<MyListItem
item={item}
/>
</TouchableOpacity>
)
}
这是 onPress 函数。正如你所看到的,这里的状态发生了变化,所以不知道为什么extraData 没有看到
onPressListItem = ( index ) => {
const copyOfSymbolsList = [...this.state.symbols];
thePressedSymbol = copyOfSymbolsList[index];
if (thePressedSymbol.iconName === 'md-star') {
thePressedSymbol.iconName = 'md-star-outline';
}else{
thePressedSymbol.iconName = 'md-star';
}
copyOfSymbolsList[index] = thePressedSymbol;
this.setState({
symbols: copyOfSymbolsList
});
}
这是我的平面列表
<FlatList
data={this.state.symbols}
extraData={this.state.symbols}
keyExtractor= {(item, index) => item.symbol}
ItemSeparatorComponent={this.renderListSeparator}
renderItem={this.renderListItem}
/>
【问题讨论】:
-
你试过
forceUpdate()吗? -
@zoonosis
PureComponent只期望简单的状态......以便比较正常工作...... -
如果您使用 lodash 深度克隆数组并尝试 const copyOfSymbolsList = _.cloneDeep(this.state.symbols);
-
@HendEl-Sahli 不确定您所说的简单状态是什么意思
标签: javascript node.js react-native expo