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

如何解决React中「列表子元素需唯一key属性」警告?

解决React列表key属性警告问题

你遇到的Warning: Each child in a list should have a unique "key" prop警告,核心原因是通过map生成StarIcon列表时,每个子元素没有设置唯一的key属性。

修复方案

直接在StarIcon标签上添加key属性,使用循环的索引i作为值即可(这里每个星星是按序列生成的,索引能保证唯一性):

<div className='flex'>
  {Array(rating)
    .fill()
    .map((_, i) => (
      <StarIcon key={i} className='h-5 text-yellow-500'></StarIcon>
    ))}
</div>

额外代码问题修正

顺便提两个代码里的小错误,避免后续出现异常:

  • Image组件的style属性需要传入对象而非字符串,修改为:
    <Image src={image} height={200} width={200} style={{ objectFit: "contain" }}></Image>
    
  • hasPrime渲染的div中,spaxe-x-2是拼写错误,应为space-x-2:
    <div className='flex items-center space-x-2 -mt-5'>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:30:55