【发布时间】:2018-05-23 05:33:04
【问题描述】:
我正在使用 React Native FlatList 在行上显示数据。以下是我的代码。
HomeScreen.js
render() {
return (
<View
style={styles.container}
onLayout={this.onLayout.bind(this)}>
<Spinner visible={this.state.isShowSpinner} animation="fade" color={APP_THEME_COLOR} />
<View style={styles.subContainerStyle}>
{facetWebView}
<AnimatedFlatList
style={styles.flatListStyle}
ref={flatListRef => this.templateFlatList = flatListRef}
data={this.state.templatePosts}
renderItem={({item}) => this.renderCellItem(item)}
/>
</View>
</View>
}
renderCellItem(item, index) {
return (
<TemplateCell
item={item}
index={index}
isPortraitMode={this.state.isPortraitMode}
didSelectItemFromCell={(item) => {
this.didSelectItemFromCell(item)
}}
/>
)
}
在 TemplateCell 中,我显示了收藏/不收藏状态。我在 TemplateCell 中将 shouldComponentUpdate 写为
shouldComponentUpdate(nextProps, nextState) {
const isItemChanged = this.props.item != nextProps.item
const isPortraitMode = this.props.isPortraitMode != nextProps.isPortraitMode
return isItemChanged || isPortraitMode
}
But still it is rendering the cell again. How can I avoid this.
我在链接https://codeburst.io/when-to-use-component-or-purecomponent-a60cfad01a81中找到了
永不变异 你可能听说过不要在 props 和 state 中改变对象和数组。如果你要改变父组件中的对象,你的“纯”子组件不会更新。尽管上游的值发生了变化,但孩子会将引用与之前的道具进行比较,而不会检测到差异。
我相信我的数组是可变的,这就是为什么更改完成的项目对象在 props 和 nextProps 中保持不变。如何避免这种情况
【问题讨论】:
-
如果您为您的
FlatList设置keyExtractor会怎样,例如keyExtractor={(item, index) => item.UNIQUE_PROP} -
@Cherniv keyExtractor={(item, index) => index}
-
什么时候再渲染,cases?
-
@RaviRaj 1. 当我单击行上的按钮以更改收藏状态时 2. 当我为平面列表加载更多时 3. 当我在同一屏幕上显示其他 UI 时
标签: android ios performance react-native react-native-flatlist