简体   繁体   English

反应索引键在地图中不起作用

[英]React index key is not working in the map

I have used index key but it's still showing errors. 我已经使用了index键,但是它仍然显示错误。 Also tried with unique id from JSON data but can't solve this. 还尝试使用JSON数据中的唯一ID,但无法解决此问题。

ERROR 错误

Warning: Each child in a list should have a unique "key" prop. 警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

const faqdata = this.props.faqData.map((faq, index) => (
    <li key={index}>
            {faq.description}
    </li>
));

Warning: Each child in a list should have a unique " key " prop. 警告:列表中的每个孩子都应该有一个唯一的“ ”道具。

You will get this warning only when two or more items in the list have been supplied with the same key , Your code looks fine for me, it shouldn't be giving this warning , please try with a console.log(index) inside the map . 仅当列表中的两个或多个项目提供了相同的键时 ,您才会收到此警告,您的代码对我来说很好,它不应发出此warning ,请尝试在控制台中使用console.log(index) map

const faqdata = this.props.faqData.map((faq, index) => {
    console.log(index);
    <li key={index}>
            {faq.description}
    </li>
});

Anti Pattern: 反模式:

You should not be using index of the map for you Key , its an antipattern, it may lead to unpredictable results. 您不应该为Key使用地图索引 ,它是反模式,它可能导致不可预测的结果。

Please check this https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318 请检查此https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

You should be using proper unique-id for your Key , like a DB id or some unique-id. 您应该为密钥使用适当的唯一ID ,例如数据库ID或某些唯一ID。

This Key is used internally to identify the DOM elements to render and not to render again. 此密钥在内部用于标识要渲染的DOM元素,而不是再次渲染。

您必须使用ID,非重复名称(或您使用的唯一名称),但要使用其索引,因为它通过其key:value对比较VDOM。

In retrospect to other answers quoting that you should not use array index as a key, as much as it is an antipattern, it will still resolve the warning. 回顾其他答案,引用您不应该将数组索引用作键,尽管它是一种反模式,它仍然可以解决警告。

What you're doing is right and should remove the warning. 您正在执行的操作是正确的,应该删除警告。 Although I suspect the warning is coming when you iterate again over the result of your faqdata . 尽管我怀疑再次faqdata的结果时会发出警告。

Every time you render something from an array, each entry should have the key attribute. 每次从数组中渲染内容时,每个条目都应具有key属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM