reactjs - 即使表格行上有唯一键,唯一键道具错误
问题描述
我不知道如何纠正这个问题。我正在使用唯一 ID,但反应仍然不高兴。我试图在每个上都这样做,但后来它抱怨重复。
<table>
<tbody>
{!loading &&
products &&
products.map((product) => (
<>
<tr>
<td key={product._id}>{product.name}</td>
<td>
<span>
<strong>{product.desc}</strong>
</span>
</td>
</tr>
</>
))}
</tbody>
</table>
解决方案
或者与其自己处理密钥,不如让 React 为您处理。我觉得它很方便:
<table>
<tbody>
{
!loading && products && React.Children.toArray(
products.map((product) => (
<tr>
<td>{product.name}</td>
<td>
<span>
<strong>{product.desc}</strong>
</span>
</td>
</tr>
))
)
}
</tbody>
</table>
所以你再也不用担心分配键了!
React.Children.toArray
以平面数组的形式返回子级不透明数据结构,并为每个子级分配键。如果你想在你的渲染方法中操作孩子的集合,特别是如果你想在传递它之前重新排序或切片 this.props.children 时很有用。
官方文档:https ://reactjs.org/docs/react-api.html#reactchildrentoarray
推荐阅读
- angular - 如何在角度4的http请求中传递url参数
- javascript - 从本地存储中获取值时 DOM 未更新
- android - 无法在真实设备中获取当前位置
- javascript - 使用矩 js(_d 和 _i)
- android - 无法使用 onLocationChanged 获取位置
- ruby-on-rails - 将“collection_select”与数组一起使用
- python - 如何在熊猫中使用具有特定顺序的sort_index
- php - 未检测到或未加载 css
- linux - nvcc 致命:编译 matlab 时不支持的 gpu 架构“compute_20”
- c# - 使用 Windows 应用程序 c#/vb.net 在浏览器中关闭单个选项卡