简体   繁体   中英

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.

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

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

Thanks to anyone who can help me!

I don't know why but I fixed it with an if statement in the equal function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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