我正在创建一个动态表。
如果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>
);
};
对于像我这样有问题的人,代码解决了这个问题。
{/* ..... */}
<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>
{/* ..... */}