简体   繁体   English

即使使用 React.memo 也会重新渲染 FlatList 项目

[英]FlatList items re-rendering even with React.memo

I am trying to render a list of items in React Native with the FlatList component but every time I fetch new data it re-renders the who list of items even with React.memo.我正在尝试使用 FlatList 组件呈现 React Native 中的项目列表,但每次我获取新数据时,它都会重新呈现项目列表,即使使用 React.memo。

Here is what my code looks like:这是我的代码的样子:

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}
/>

Component.js组件.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)

Every time the onEndReached function gets triggered and calls the loadMore function, all FlatList items get re-rendered, it console.log 'I am rendering' every single time and causes the error virtualizedlist you have a large list that is slow to update每次onEndReached function 被触发并调用 loadMore function 时,所有 FlatList 项目都会重新渲染,它 console.log '我正在渲染'每次都会导致错误virtualizedlist you have a large list that is slow to update

Thanks to anyone who can help me!感谢任何可以帮助我的人!

I don't know why but I fixed it with an if statement in the equal function我不知道为什么,但我用equal的 function 中的 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
}

Hope this could help someone else.希望这可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM