Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/66064873/flatlist-items-re-rendering-even-with-react-memo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...