javascript - 将索引作为键,这是一个好习惯吗?还是我应该使用 react-uuid?
问题描述
嗨,有一个需要呈现为一组按钮的项目列表,我只想知道哪个是好的和最简单的解决方案。
第一个选项只是将密钥用作项目密钥
const sampleoutput =[];
for (const [key, value] of Object.entries(sampleItem)) {
sampleoutput.push(<li>
<a key={key}
href="#!"
onClick={value.onClick}
>
{value.title}
</a>
</li>);
}
第二种解决方案是使用 react-uuid
import uuid from "react-uuid";
sampleItem.map((value) => {
return (<li>
<a key={uuid()}
href="#!"
onClick={value.onClick}
>
{value.title}
</a>
</li>);
})
我还想考虑性能,第二个选项有另一组流程来生成密钥。我有点担心第一个选项,即使它更简单,因为这篇文章https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
预先感谢您的建议。
解决方案
React expects stable static key which will last till component life
Using this key, it decide whether new component instance need to
create or have to update existing component instance property.
react-uuid
每当您调用时都会生成动态密钥,uuid()
并且它将在每次渲染时重新生成。
每当发生重新渲染时,动态生成的新密钥将导致创建一个新的组件实例。
最好只从集合中创建一个密钥,该密钥不会更改并存在于集合中,直到数据存在于集合中。
尽量避免react-uuid
并使用第一种方法。
推荐阅读
- android - Android 导航组件 - 向上导航打开相同的片段
- android - 如何正确应用谷歌服务插件?
- r - R - ggplot2 - 尽管数据单调,但取决于多个变量的绘图和 aes 创建锯齿形
- java - 如何从父项目覆盖 Spring Data Mongo 版本?
- node.js - nodejs使用套接字接收数据。但它被分割了
- oracle - 如何将 SELECT 到模式中的任何表授予角色 (Oracle)
- android - 如何在 Android 8/9 上为 OkHttp 3.12.x 启用 TLSv1.3?
- web - 如何改进浏览器缓存
- powershell - 停止远程使用文件的进程
- c# - 如何在从网络摄像头获取的 c# Emgu cv 帧中创建服务器 RTSP?