reactjs - 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>
);
};
解决方案
对于像我这样有问题的人,代码解决了这个问题。
{/* ..... */}
<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>
{/* ..... */}
推荐阅读
- php - 如何拆分 json - 使用 laravel
- ruby-on-rails - 无法连接到服务器 - 错误“/var/run/postgresql/.s.PGSQL.5432”?
- scala - 过滤一个数据帧的值(如果存在且不存在于另一个数据帧中)
- php - 无法使用 Facebook Business SDK 创建广告集
- javascript - 打开花括号 { 的键码是什么
- android - Firebase FCM 变得非常不稳定。寻找解决方案/替代方案
- dart - 如果没有其他情况如何创建内联
- android - 无法解析 GoogleSignInClient
- android - 如何使用差异项目回调更新回收站视图中的项目?
- reactjs - 反应头像编辑器没有上传按钮