【发布时间】:2018-02-07 10:20:05
【问题描述】:
我正在尝试从从 api 获取的 json 中呈现 FlatList,但我不断收到此错误:
Warning: Each child in an array or iterator should have a unique "key" prop.
Check the render method of `VirtualizedList`.
相关代码:
<FlatList
data={this.props.tunes}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
<Item
key={item.id}
title={item.title}
composer={item.composer}
year={item.year}
/>
}}
/>
我确信有一个简单的解决方法,但经过几天尝试不同的方法后,我还没有找到它。感谢您的帮助!
【问题讨论】:
-
您确定每件商品的 item.id 不同吗?并确保数据中没有重复项。
-
也许这就是我感到困惑的地方。 json 中没有 item.id,但我认为 React 可能会在这种情况下提供它。在将数据提供给 FlatList 之前,我是否必须映射 json 为每个项目添加一个 id?
-
您需要自己创建密钥。您可以执行
item.name + index之类的操作,或者每个项目的某些内容可以是唯一的并且不会更改 -
你试过
keyExtractor={(item, index) => index}吗? -
很高兴为您提供帮助:)
标签: reactjs react-native react-native-flatlist