0

我正在尝试使用 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 '我正在渲染'并导致错误virtualizedlist you have a large list that is slow to update

感谢任何可以帮助我的人!

4

1 回答 1

1

我不知道为什么,但我用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
}

希望这可以帮助别人。

于 2021-02-05T14:42:20.637 回答