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

React列表渲染出现Each child in a list should have a unique "key" prop警告如何修复

警告触发原因

React 渲染通过map遍历生成的列表元素时,需要为每个列表子项设置唯一的key属性,用于虚拟DOM Diff 算法识别元素的增删、排序变更,既可以提升渲染性能,也能避免列表状态错乱的问题。你当前代码中遍历experts数组生成<Expert>组件时未配置key属性,因此触发了该警告。

解决方法

key 需要选取每个列表项唯一且固定不变的属性,优先选择业务唯一标识(如后台返回的id),静态无变更的列表也可以用名称等唯一字段,不推荐直接用数组下标作为key(列表有增删、排序操作时会导致状态错乱或不必要的重渲染)。

你可以直接修改遍历渲染的代码,添加key属性即可:

// 这里用expert.name作为key,你也可以后续给每个专家对象新增id字段,用key={expert.id}更稳妥
experts.map(expert => <Expert key={expert.name} expert={expert}></Expert>)

修改后的完整组件代码如下:

const Experts = () => {
    const experts = [{
            img: image1,
            category: 'Dentist',
            name: 'Dr. Robartis',
            expertize: 'DMD,FACE'
        },
        {
            img: image2,
            category: 'Dentist',
            name: ' Dr. Linda Davis',
            expertize: 'CDT'
        },
        {
            img: image3,
            category: 'Dentist',
            name: 'Zakaria Smith',
            expertize: 'FACDS,DDS'
        },
        {
            img: image4,
            category: 'Dentist',
            name: 'Maria',
            expertize: 'FADG,DMD'
        }
    ]
    return (
        <div className="container" id="experts">
            <h2 className="mb-5">Award Winning Dentists</h2>
            <div className="row">
                {
                    experts.map(expert => <Expert key={expert.name} expert={expert}></Expert>)
                }
            </div>
        </div>
    );
};

export default Experts;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:06:03