You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native出现Encountered two children with the same key错误,如何解决?

解决FlatList重复key与数组重复问题
  • 先修复keyExtractor的错误:你代码里的keyExtractor={(message) => message.id.toString}是把toString函数本身作为key,而非调用它生成的字符串,导致所有item的key都是同一个函数引用,必然触发"重复key"错误。改成message.id.toString(),调用toString方法拿到id的字符串形式,保证每个item的key唯一。

  • 排查数组重复的根源:如果修复key后仍存在内容重复,先检查messages数组里是否真的有id相同的元素。可以在组件中添加一行代码:console.log('去重后的id数量:', [...new Set(messages.map(m => m.id))].length),对比原数组长度就能判断是否存在重复id。另外还要排查数据来源,比如接口返回是否重复,或者状态更新时有没有不小心添加重复项。

修正后的代码:

return (    
    <SafeAreaView style={styles.container}>
        <Screen> 
            <FlatList
                data={messages} 
                keyExtractor={(message) => message.id.toString()}
                renderItem={({item}) => 
                    <ListItem
                        title={item.title}
                        subTitle={item.description}
                        image={item.image}
                        onPress={() => console.log("Message selected", item)}
                        renderRightActions={() => (<ListItemDeleteAction onPress={() => handleDelete(item)}/>)}
                    />
                }
                ItemSeparatorComponent={ListItemSeparator}
            /> 
        </Screen>
    </SafeAreaView>
)

内容的提问来源于stack exchange,提问作者Valeria Alonso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:50:46