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

React列表key警告消除:如何为多元素设置唯一key?

解决React列表key警告的修改方案

修改后的代码

import React, { useState } from "react";
import "./App.css";

// 导入图片文件
import img0 from "./seasons/0.png";
import img1 from "./seasons/1.png";
import img2 from "./seasons/2.png";
import img3 from "./seasons/3.png";
import img5 from "./seasons/cap.png";

// 创建季节数组对象,将原key字段改为toggleId避免和React的key prop冲突
const season = [
    {
        id: "10",
        toggleId: "1",
        title: "Spring",
        img: img1,
    },
    {
        id: "20",
        toggleId: "2",
        title: "Summer",
        img: img0,
    },
    {
        id: "30",
        toggleId: "3",
        title: "Autumn",
        img: img2,
    },
    {
        id: "40",
        toggleId: "4",
        title: "Winter",
        img: img3,
    },
    {
        id: "50",
        toggleId: "5",
        title: "Instructions",
        img: img5,
    },
];

function Season() {
    // 初始化toggle状态为null,避免undefined
    const [toggle, setToggle] = useState(null);

    return (
        <div className="container">
            {season.map(({ id, toggleId, title, img }) => {
                return (
                    // 使用唯一的id作为React列表项的key
                    <div key={id}>
                        <h1 onClick={() => setToggle(toggleId)}>{title}</h1>
                        {toggle === toggleId ? (
                            <div>
                                <img
                                    style={{
                                        width: 350,
                                        height: 350,
                                        borderRadius: "50%",
                                    }}
                                    src={img}
                                    alt={title} // 添加alt属性提升可访问性
                                />
                            </div>
                        ) : null}
                    </div>
                );
            })}
        </div>
    );
}

export default Season;

核心修改说明

  • 把数组内的key字段重命名为toggleId,避免和React的特殊key prop命名冲突,消除逻辑混淆
  • 确保列表项的key使用数组中唯一的id值,这是React官方推荐的列表项唯一标识方案
  • 初始化useState为null,避免状态处于undefined的异常情况
  • 给图片添加alt属性,提升页面可访问性
  • 将borderRadius: 400 / 2简化为borderRadius: "50%",语义更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:35:20