首页 > 解决方案 > 将索引作为键,这是一个好习惯吗?还是我应该使用 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

预先感谢您的建议。

标签: javascriptreactjsreact-nativefor-loopforeach

解决方案


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并使用第一种方法。


推荐阅读