问题
How to optimize performance of Flatlist when we have large data.
My list has both an image and an text description.
I want to find a way to increase performance of list and remove extra images loaded from the cache list and make the list not heavy.
回答1:
There is something called PureComponent in react native. If you create your FlatList
item as PureComponent
, you can see lot of improvement. It will not rerender items untill data has been changed.
Something like this :
class MyListItem extends React.PureComponent {
}
Here is reference link
Even the library suggested by Nino9612 react-native-optimized-flatlist is also using the same concept, as you can see code of their FlatListItem
回答2:
The FlatList component is supposed to be a performant solution for displaying large lists of data in your app. It only displays some of the items in the list according to which items are currently visible. That said there are a few tricks that help to make it faster / lighter
- It helps if your flat list items are of the same height (assuming a vertical scrolling flatlist). In this case you can use the getItemLayout prop to set the height of the FlatList and skip the dynamic calculations https://facebook.github.io/react-native/docs/flatlist#getitemlayout
- You might want to try to use removeClippedSubviews prop to see if it helps https://facebook.github.io/react-native/docs/flatlist#removeclippedsubviews
- Don't load all you data at once but use some form of pagination in your fetch call (if possible). You can then fetch more data using onEndReached for example.
- Make sure that your FlatList only updates when it's supposed to. I usually use shouldComponentUpdate in the component that contains the FlatList to make sure it only updates when its data change and not when some other state/ prop variable that I don't care about changes
- If your FlatList items contain images you should consider caching them
I'm sure there are more things you can do, but that's it from me :)
回答3:
There are multiple npm packages promising to improve the performance of the default react-native flatlist for example https://www.npmjs.com/package/recyclerlistview#demo or https://github.com/stoffern/react-native-optimized-flatlist . I didnt test them but they seem to improve the overall performance. If you not working with local data but with data you receive from a network maybe you should take a look into pagination to improve the list speed and also (mobile) data usage
来源:https://stackoverflow.com/questions/52217044/reactnative-flatlist-optimization-performance-of-flatlist-items