[英]React Native FlatList key
I have a FlatList which renders a custom component "Card".我有一个 FlatList,它呈现一个自定义组件“卡片”。 I am passing as keyExtractor this function:
我将这个函数作为 keyExtractor 传递:
const keyExtractor = (item) => item.id;
And my renderItem function looks like this:我的 renderItem 函数如下所示:
const renderItem = ({item, index}) => <Card {...item} />
My question is: should I pass a key to the Card component?我的问题是:我应该将密钥传递给 Card 组件吗? I mean, should I do this
我的意思是,我应该这样做吗
const renderItem = ({item, index}) => <Card key={item.id} {...item} />
to avoid my flatlist re-render components and improve the performance of my list?避免我的 flatlist 重新渲染组件并提高我的列表的性能? I have seen some people doing this... but I have never done it.
我见过一些人这样做……但我从来没有这样做过。 If the answer is yes, why we need keyExtractor if each rendered component have a key?
如果答案是肯定的,如果每个渲染的组件都有一个键,为什么我们需要 keyExtractor?
Of course, if I pass a key to my custom component I will do this on its implementation:当然,如果我将密钥传递给我的自定义组件,我将在其实现上执行此操作:
return <View key={props.key}>...</View>
Thank you.谢谢你。
You should have a unique property in your data and use it as a key.您的数据中应该有一个唯一的属性并将其用作键。 There is no need to pass the
key
to your Card
component.无需将
key
传递给您的Card
组件。
If your data is something like this:如果你的数据是这样的:
data = [
{
id: 'a12f56e5',
name: 'me',
age: 24
}
// ...
];
then you can use id
as key.那么你可以使用
id
作为密钥。
Also, please take a look at this to improve your FlatList performance另外,请看一下 这个以提高您的 FlatList 性能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.