在js中为数组的每个元素创建一个唯一的id?

Create a unique id for each element of array in js?

我有一个用例,我想在遍历数组时为数组的每个元素分配唯一的 ID。请注意,此数组包含重复值。我想在反应元素中使用索引作为键,但 linter 规则不允许我使用索引作为键。 我想到了使用 System tics? 有没有一种方法可以获得系统滴答,以便在每条指令执行时,我都能得到一个新值? 如果是,建议的精度是多少?

尽管@Archer 的方法可能已经足够可行,但我提供了这个解决方案,我主要在 OP 描述的情况下使用...

var createId = (
  /*  [https://github.com/broofa/node-uuid] - Robert Kieffer  */
  (window.uuid && (typeof window.uuid.v4 === 'function') && window.uuid.v4)

  /*  [https://gist.github.com/jed/982883]  - Jed Schmidt     */
  || function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
);


console.log('createId() : ', createId());
console.log('createId() : ', createId());
console.log('createId() : ', createId());
.as-console-wrapper { max-height: 100%!important; top: 0; }

我建议既不使用索引也不使用系统刻度,因为这两个选项都会让您远离密钥应该提供的功能。

文档中说:"Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity"

所以有多种选择:

  • 您可以创建一个函数来生成唯一的 keys/ids/numbers/strings 并使用它
  • 您可以使用现有的 npm 包,如 uuid、uniqid 等
  • 您还可以生成随机数,如 new Date().getTime();并在其前面加上您正在迭代的项目中的内容以保证其唯一性
  • 最后,您可以使用从数据库中获取的唯一 ID(如果没有看到您的数据很难说)

但是:密钥应该是稳定的、可预测的和唯一的。不稳定的键(如 Math.random() 生成的键)将导致不必要地重新创建许多组件实例和 DOM 节点,这会导致子组件的性能下降和丢失状态。

您可以在此处阅读更多内容:https://reactjs.org/docs/reconciliation.html#keys

所以没有完美的答案。这取决于您的用例...