You need to enable JavaScript to run this app. React map渲染子组件报unique "key" prop ESLint警告如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React map渲染子组件报unique "key" prop ESLint警告如何解决?

问题根因

你遇到的警告核心原因是map遍历返回的直接子节点是React Fragment(<>语法糖),但你没有给这个最外层的Fragment添加key,所有key都加在了Fragment内部的div节点上,React不会将内部节点的key识别为列表项的key。
另外你的代码还存在语法问题:组件return语句中直接返回了两个并列的div节点,不符合React单根节点的要求,也会触发运行报错。

解决方案
  • 替换map返回值的<>语法糖为完整的<React.Fragment>标签,给这个标签添加唯一key,优先用业务唯一值(比如detail.heading),不要用索引index避免列表排序时出现渲染异常
  • 给组件最外层的两个并列div套一个公共根节点(比如普通div或者Fragment)
  • 移除冗余key:列表项内部的small、strong标签,以及外层flex-container上的key="test"都属于不必要的key,不需要额外添加
修正后代码
const EmployeeDetails = ({ employeeid }) => {
    return (
            {/* 外层套根节点解决并列节点报错问题 */}
            <div>
            <div>
            <strong>Employee Overview Details</strong>
            </div>
            <div className="flex-container">
            {employeeOverviewDetails.map((detail) => {
            // 给map返回的直接子节点Fragment加唯一key
            return (
            <React.Fragment key={detail.heading}>
            {detail.heading === 'Employee ID' && (
            <div
                className="indiviual-flex"
                >
                <small>
                {detail.heading}
                </small>
                <br />
                <strong>
                {employeeid}
                </strong>
            </div>
            )}
            {detail.heading !== 'Employee ID' && (
            <div
                className="indiviual-flex"
                >
                <small>{detail.heading}</small>
                <br />
                <strong>{detail.value}</strong>
            </div>
            )}
            </React.Fragment>
            )
            })}
            </div>
            </div>
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:06:04