You need to enable JavaScript to run this app. React列表渲染报Each child in a list should have a unique key错误,已加key仍报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React列表渲染报Each child in a list should have a unique key错误,已加key仍报错如何解决?

问题根因

React列表渲染规则要求key属性必须绑定在map返回的最外层根元素上。当前代码中map每次遍历返回的最外层元素是<Col>组件,key却绑定在了内层的<PriceCard>组件上,React无法识别到列表直接子节点的唯一标识,因此触发key缺失警告。

修复方案

将key属性移动到外层的<Col>组件上即可,修改后代码如下:

{Data.map(datas => <Col lg={4} key={datas.id}>
    <PriceCard 
        title={datas.title} 
        text={datas.text} 
        price1={datas.price1} 
        price1text={datas.price1text} 
        price2={datas.price2} 
        price2text={datas.price2text} 
        price3={datas.price3} 
        price3text={datas.price3text} 
        price4={datas.price4} 
        price4text={datas.price4text} 
        price5={datas.price5} 
        price5text={datas.price5text}  
        imgUrl={datas.imgUrl} 
    />
</Col>)}

注意事项

  • 除非列表为完全静态、不会发生增删/排序操作,否则不要使用数组下标作为key值,避免引发渲染异常
  • 确保绑定的datas.id为全局唯一字段,无重复值

内容的提问来源于stack exchange,提问作者Onur Yüksekkaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:45:08