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
448 views
in Technique[技术] by (71.8m points)

javascript - react native 100+ items flatlist very slow performance

I have a list just simple text that rendering into flatlist on react native but I am experiencing very very slow performance which makes app unusable.

How can I solve this? My code is:

<FlatList
  data={[{key: 'a'}, {key: 'b'} ... +400]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is my suggestions:

A. Avoid anonymous arrow function on renderItem props.

Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called.

B. Try add initialNumToRender prop on your FlatList

It will define how many items will be rendered for the first time, it could save some resources with lot of data.

C. Define the key prop on your Item Component

Simply it will avoid re-render on dynamically added/removed items with defined key on each item. Make sure it is unique, don't use index as the key! You can also using keyExtractor as an alternative.

D. Optional optimization

Try use getItemLayout to skip measurement of dynamic content. Also there is some prop called maxToRenderPerBatch, windowSize that you can use to limit how many items you will rendered. Refer to the official doc to VirtualizedList or FlatList.

E. Talk is Cheap, show me the code!

// render item function, outside from class's `render()`
const renderItem = ({ item }) => (<Text key={item.key}>{item.key}</Text>);

// we set the height of item is fixed
const getItemLayout = (data, index) => (
  {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
);

const items = [{ key: 'a' }, { key: 'b'}, ...+400];

function render () => (
  <FlatList
    data={items}
    renderItem={renderItem}
    getItemLayout={getItemLayout}
    initialNumToRender={5}
    maxToRenderPerBatch={10}
    windowSize={10}
  />
);

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

...