gpt4 book ai didi

reactjs - 防止 FlatList 在状态改变时重新渲染整个列表

转载 作者:行者123 更新时间:2023-12-04 14:58:01 27 4
gpt4 key购买 nike

我有一个数组 posts在我通过 onEndReached 更新的 redux reducer 中我的 Prop FlatList .问题是,每次状态更改时,都会重新呈现整个列表,而不是受影响的帖子项。

// Posts Feed Screen

const posts = useSelector(state => state.posts)

const renderItem = useCallback(
({ item }) => (
<Post post={item} />
),
[]
)
const keyExtractor = useCallback(
(item, index) => `${item.id}${index}`,
[]
)

return (
<FlatList
ref={ref}
data={posts}
keyExtractor={keyExtractor}
renderItem={renderItem}
onEndReached={onEndReached}
onEndReachedThreshold={0.6}
showsVerticalScrollIndicator={false}
removeClippedSubviews
/>
)



// Post Component

const Post = ({ post }) => {
return (
<View style={styles.post}>
<PostHeader />
<View style={styles.postBody}>
<PostContent />
<PostFooter />
</View>
</View>
)
}

const isEqual = (prevProps, nextProps) => {
return prevProps.post.id === nextProps.post.id
}

export default React.memo(Post, isEqual)
如您所见,我正在使用 useCallbackrenderItem函数,也使用 React.memo关于我的 Post Component 的导出- 然而, FlatList仍然在状态更改时呈现每个帖子项。
我在这里错过了什么?

最佳答案

我将发表我的评论作为答案,因为最终问题是这样解决的:
这实际上比看起来更简单。发生的情况是,当您每次创建新引用时将“引用类型”作为 Prop 传递时,组件将重新渲染。
因此,在更新“帖子”的 reducer 中,您应该确保不是每次都创建新列表,而是仅更新列表中单个帖子的属性。
例如,避免传播运算符。此外,帖子组件不应将帖子作为 Prop ,而实际上是帖子的 ID,并使用 useSelector 找到它本身,而 useSelector 又应返回属性的值。
因此,例如,最好为每个显示的属性显示一个 useSelector,而不是整个帖子的单个 useSelector。
原因是react渲染引擎比较使用“==”来发现差异并决定如何渲染。
并且两个对象可以逐个属性进行完全相同的比较,但由于它们是不同的实例,因此返回不同。
这里的关键是只更新 reducer 内部需要更新的属性,同时确保在 useSelectors 中返回值类型。

关于reactjs - 防止 FlatList 在状态改变时重新渲染整个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67577312/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com