反应原生 100 多个项目 flatlist 性能很慢 [英] react native 100+ items flatlist very slow performance

查看:35
本文介绍了反应原生 100 多个项目 flatlist 性能很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表只是简单的文本,可以在 React Native 上渲染到 flatlist,但我遇到了非常非常慢的性能,这使得应用程序无法使用.

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

推荐答案

以下是我的建议:

A.避免在 renderItem 道具上使用匿名箭头函数.

A. Avoid anonymous arrow function on renderItem props.

renderItem 函数移到渲染函数的外部,这样它就不会在每次调用渲染函数时重新创建自己.

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

B.尝试在您的 FlatList

它会定义第一次渲染多少个项目,它可以节省一些资源和大量数据.

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

C.在您的项目组件上定义 key 道具

C. Define the key prop on your Item Component

简单地说,它将避免在每个项目上定义了key 的动态添加/删除的项目上重新渲染.确保它是唯一的,不要使用 index 作为键!您也可以使用 keyExtractor 作为替代.

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.可选优化

尝试使用 getItemLayout 跳过动态内容的测量.还有一些叫做 maxToRenderPerBatchwindowSize 的道具,你可以用它来限制你将渲染的项目数量.参考官方文档 VirtualizedListFlatList.

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.话不多说,给我看代码!

// 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}
  />
);

这篇关于反应原生 100 多个项目 flatlist 性能很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆