【问题标题】:React Keys - unique in that List or unique in the whole page?React Keys - 在该列表中是唯一的还是在整个页面中是唯一的?
【发布时间】:2022-12-11 19:18:53
【问题描述】:

所以我在同一个页面上有多个列表,它们具有来自数据库的相同 ID。

我收到“每个元素都需要一个唯一键”的错误

我已经对这个主题进行了一些研究,但我不太明白:

键是否需要在该列表或整个页面列表中是唯一的?

比方说:

id=['guid1', 'guid2', 'guid3']

组件渲染:

<ul className="list1">
 id.map((el) => <li key={el}>test</li>);
</ul>

<ul className="list2">
 id.map((el) => <li key={el}>test</li>);
</ul>

这样可以吗?

谢谢。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    需要使用迭代项作为键。不是这里的整个列表id

    id.map((item) => <li key={item}>{item}</li>);
    

    【讨论】:

    • 对不起。那是一个错字。我修改了我的问题。我在问别的东西:)
    【解决方案2】:
    const id=['guid1', 'guid2', 'guid3']
    <ul className="list1">
    {
    id.map((idx,item) => <li key={idx}>{item}</li>)}</ul>
    }
    <ul className="list2">
    {
     id.map((idx,item) => <li key={idx}>{item}</li>)
    }
    </ul>
    
    您可以生成数组的每个元素的索引并将其用作这样的键。键帮助 React 识别哪些项目已更改、添加或删除。最好提供密钥。
    Keys have to be unique for every element you can use entire element as keys.
    A “key” is a special string attribute you need to include when creating
     lists of elements in React. Keys are used in React to identify which items
     in the list are changed, updated, or deleted. In other words, we can say 
    that keys are used to give an identity to the elements in the lists.
    

    【讨论】:

    • 对不起。那是一个错字。我修改了我的问题。我在问别的东西:)
    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多