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

已为列表项设唯一key仍触发Each child in a list should have a unique 'key' prop警告

解决React列表项已设key仍报"Each child in a list should have a unique 'key' prop"警告的问题
  • 确认key值的唯一性
    你当前用label作为MenuItem的key,但如果countryArr中存在重复的label,就会触发警告。可以先通过console.log(countryArr)检查数组内的label是否全部唯一。如果label可能重复,建议改用唯一值作为key,比如value(确保value全局唯一),或者组合字段如${label}-${value},若数组有id字段优先用id。

  • 优化条件渲染结构
    你使用的!!countryArr?.length && ...短路写法,可能导致React误将布尔值视为列表的子元素(虽然概率低,但属于潜在风险)。建议改为完整的三元表达式渲染:

    {countryArr?.length ? (
      countryArr.map(({ label, value }) => (
        <MenuItem key={value} value={value}>
          {label}
        </MenuItem>
      ))
    ) : null}
    
  • 排查嵌套组件的隐式列表
    检查<Select>组件内部是否存在其他未设置key的列表渲染逻辑,比如自定义下拉选项组件内部的map循环是否遗漏key。

修改后的示例代码

<FormControl className="registerInputs">
  <InputLabel htmlFor="name-multiple">Country</InputLabel>
  <Select
    value={country}
    placeholder="Country"
    input={<Input id="name-multiple" />}
    onChange={(e) => selectCountryHandler(e.target.value)}
  >
    {countryArr?.length ? (
      countryArr.map(({ label, value }) => (
        <MenuItem key={value} value={value}>
          {label}
        </MenuItem>
      ))
    ) : null}
  </Select>
</FormControl>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:40:25