React Native:无法修复 FlatList 键警告
React Native: Can't fix FlatList keys warning
我正在尝试渲染从 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}
/>
}}
/>
我确信有一个简单的修复方法,但在尝试了几天不同的东西后我还没有找到它。感谢您的帮助!
看起来您需要将 key
更改为 id
,因为您在 keyExtractor
中写入 item.id
并确保您有 id,并且每个组件都不同:
<FlatList
data={this.props.tunes}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
<Item
id={item.id} //instead of key
title={item.title}
composer={item.composer}
year={item.year}
/>
}}
/>
或者如果您没有唯一密钥,请使用 keyExtractor={(item, index) => index}
我正在尝试渲染从 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}
/>
}}
/>
我确信有一个简单的修复方法,但在尝试了几天不同的东西后我还没有找到它。感谢您的帮助!
看起来您需要将 key
更改为 id
,因为您在 keyExtractor
中写入 item.id
并确保您有 id,并且每个组件都不同:
<FlatList
data={this.props.tunes}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
<Item
id={item.id} //instead of key
title={item.title}
composer={item.composer}
year={item.year}
/>
}}
/>
或者如果您没有唯一密钥,请使用 keyExtractor={(item, index) => index}