首页 > 解决方案 > Reactjs:如果有条件地渲染,列表返回一个“..应该有一个唯一的'key'prop”错误

问题描述

我正在创建一个动态表。

如果 React 有条件地渲染,它会返回错误,但如果没有条件地渲染,错误不会显示。

错误:警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

如何解决这个问题呢?

const Table = () => {

  const columns = [
    { id: 1, title: "Name", accessor: "name" },
    { id: 2, title: "Server", accessor: "server", filter: true },
    { id: 3, title: "Profile", accessor: "profile", filter: true, sort: true },
    { id: 4, title: "MAC Address", accessor: "mac-address" },
    { id: 5, title: "Uptime", accessor: "uptime" },
    { id: 6, title: "Bytes in", accessor: "bytes-in" },
    { id: 7, title: "Bytes out", accessor: "bytes-out" },
    { id: 8, title: "Comment", accessor: "comment", filter: true, sort: true },
  ];
 
  return (
      <table>
        <thead>
          <tr>
            {columns.map((col) => (
              // not throw error
              // <th
              //   className={getClassNamesFor(col.accessor)}
              //   name={col.accessor}
              //   onClick={handleSort}
              //   key={col.id}
              // >
              //   {col.title}
              // </th>

              <>
                {/* throw error */}
                {col.sort ? (
                  <th
                    className={getClassNamesFor(col.accessor)}
                    name={col.accessor}
                    onClick={handleSort}
                    key={col.id}
                  >
                    {col.title}
                  </th>
                ) : (
                  <th name={col.accessor} key={col.id}>
                    {col.title}
                  </th>
                )}
              </>
            ))}
          </tr>
        </thead>
        <tbody>
         // ...
        </tbody>
      </table>
  );
};

标签: reactjs

解决方案


对于像我这样有问题的人,代码解决了这个问题。

{/* ..... */}
<thead>
  <tr>
    {columns.map((col) => (
      <Fragment key={col.id}>
        {col.sort ? (
          <th
            className={getClassNamesFor(col.accessor)}
            name={col.accessor}
            onClick={handleSort}
          >
            {col.title}
          </th>
        ) : (
          <th name={col.accessor}>{col.title}</th>
        )}
      </Fragment>
    ))}
  </tr>
</thead>
{/* ..... */}

推荐阅读