我正在尝试使用 FlatList 组件在 React Native 中呈现项目列表,但每次我获取新数据时,它都会重新呈现项目列表,即使使用 React.memo。
这是我的代码的样子:
const data = [
{ _id: 1, text: 'Hello World' },
{ _id: 2, text: 'Hello' },
{ ... }
]
const renderItem = ({ item }) => (<Component item={item} />)
const loadMore = () => {
//Fetching data from db and adding to data array
}
<FlatList
data={data}
keyExtractor={item => item._id}
renderItem={renderItem}
onEndReached={loadMore}
removeClippedSubviews={true}
/>
组件.js
const Component = ({ item }) => {
console.log('I am rendering')
return (
<Text>{item.text}</Text>
)
}
const equal = (prev, next) => {
return prev.item.text === next.item.text
}
export default React.memo(Component, equal)
每次 onEndReached
函数被触发并调用 loadMore 函数时,所有 FlatList 项目都会重新渲染,它每次都 console.log 'I am rendering' 并导致错误 virtualizedlist you have a large list that is slow to update
< /p>
感谢任何能帮助我的人!
答案 0 :(得分:0)
我不知道为什么,但我在 equal
函数中使用 if 语句修复了它
//Changing this
const equal = (prev, next) => {
return prev.item.text === next.item.text
}
//To this
const equal = (prev, next) => {
if(prev.item.text !== next.item.text) {
return false;
}
return true
}
希望这可以帮助其他人。