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

Next.js13.1列表子元素缺唯一key prop警告的解决方法咨询

解决Next.js 13.1中列表子元素缺少唯一key的警告

在Next.js 13.1开发时,控制台触发了React的列表key警告,提示Each child in a list should have a unique "key" prop,问题出在Links组件的两处数组循环渲染逻辑里——生成<ul>和<li>的循环都未设置唯一key属性。

修改方案

需要给两个循环生成的元素分别添加唯一key:

  • 外层循环生成<ul>时,用每个分组的heading作为key(所有分组标题唯一,可作为稳定标识)
  • 内层循环生成<li>时,优先使用子项的唯一id,没有id则补全,或结合外层heading与子项name生成唯一key(避免不同分组下同名项冲突)

修改后的完整代码

import styles from "./styles.module.scss";
import Link from "next/link";

export default function Links() {
  return (
    <div className={styles.footer_links}>
      {
        links.map((group) =>(
          {/* 给ul添加唯一key,使用分组heading */}
          <ul key={group.heading}>
            {
              group.heading === "SHOPPAY" ? (
              <img src="../images/logo.png" alt="Shoppay Logo" />
              ) : (
                    <b>{group.heading}</b>
              )}
            {
              group.links.map((item) =>(
                {/* 给li添加唯一key,优先用item.id,无id则用heading+name组合 */}
                <li key={item.id || `${group.heading}-${item.name}`}>
                  <Link href={item.link}>{item.name}</Link>
                </li>
              ))
            }
          </ul>
        ))
      }
    </div>
  );
}

const links = [
  {
    heading: "SHOPPAY",
    links: [
      {
        id: 1,
        name: "About us",
        link: "/about",
      },
      {
        id: 2,
        name: "Contact us",
        link: "",
      },
      {
        id: 3,
        name: "Social Responsibility",
        link: "",
      },
    ],
  },
  {
    heading: "HELP & SUPPORT",
    links: [
      {
        id: 4,
        name: "Shipping Info",
        link: "",
      },
      {
        id: 5,
        name: "Returns",
        link: "",
      },
      {
        id: 6,
        name: "How To Order",
        link: "",
      },
      {
        id: 7,
        name: "How To Track",
        link: "",
      },
      {
        id: 8,
        name: "Size Guide",
        link: "",
      },
    ],
  },
  {
    heading: "CUSTOMER SERVICE",
    links: [
      {
        id: 9,
        name: "Customer service",
        link: "",
      },
      {
        id: 10,
        name: "Terms and Conditions",
        link: "",
      },
      {
        id: 11,
        name: "Consumers(Transactions)",
        link: "",
      },
      {
        id: 12,
        name: "Take our feedback survey",
        link: "",
      },
    ],
  },
];

额外说明

  • 把原代码中依赖数组索引的i===0判断,改为直接判断分组标题,避免数组顺序变化导致渲染异常
  • 给所有子link项补全了唯一id,这是React官方推荐的key使用方式(优先用稳定的唯一标识,而非索引)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:45:28