[英]fixing warning ///Each child in a list should have a unique "key" prop
[英]Each child in a list should have a unique key prop
这是该站点的工作示例的链接: https://codesandbox.io/s/eloquent-kapitsa-kk1ls
我遇到的问题是 Buttons.js:
import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import registerIcons from "./FontAwesome";
registerIcons();
const DATA = [
{
href: "https://github.com/",
icon: ["fab", "github"],
label: "Github"
},
{
href: "https://www.linkedin.com/in//",
icon: ["fab", "linkedin"],
label: "LinkedIn"
},
{
href: "...",
icon: ["fas", "file-alt"],
label: "Resume"
},
{
href: "mailto:",
icon: ["fas", "paper-plane"],
label: "Email me"
}
];
const Icon = ({ href, icon, label }) => {
return (
<span className="button">
<a href={href} target="_self" rel="noopener noreferrer">
<FontAwesomeIcon className="icon" icon={icon} size="3x" />
<span className="icon_title">{label}</span>
</a>
</span>
);
};
class Buttons extends Component {
render() {
return (
<div>
{DATA.map(props => (
<Icon {...props} />
))}
</div>
);
}
}
export default Buttons;
我查看了与此问题相关的其他主题,但没有一个与我的情况类似。 我没有将参数传递给渲染方法 - 只是获取现有变量并将其映射以生成我的 output。
除了 DATA 数组的其他一些排列之外,我还尝试将Buttons
渲染方法更改为下面的代码,但没有太大进展。
<div key={DATA.label}>
{DATA.map(props => (
<Icon {...props} />
))}
</div>
我还阅读了关于键的 React 文档,但没有成功。
你应该用这个改变代码:
<div>
{DATA.map((props,i) => (
<Icon key={i} {...props} />
))}
</div>
因为建议不要使用索引作为组件的键。 我会说添加一个随机数并执行以下操作
<div>
{DATA.map((props,i) => (
<Icon key={Math.random()*1000*i} {...props} />
))}
</div>
如果您的 object 中没有任何唯一键,这是一种相当通用的方法。
密钥需要 go 就这样:
<div key={DATA.label}>
{DATA.map(props => (
<Icon key={props.label} {...props} />
))}
</div>
正如你可能在 React 文档中看到的关于你引用的键的那样,他们说
选择键的最佳方法是使用一个字符串,该字符串在其兄弟项中唯一标识一个列表项。
DATA 数组中的每个对象都有唯一的字符串,您可以使用其中任何一个key={props.href}
或key={props.icon[1]}
。 我在上面的答案中使用了 props.label 但关键是它不必在全世界都是独一无二的,它只需要与列表中的其他项目相比是独一无二的。
尝试
<Icon {...props} key={props.href} />
来自反应文档
一个好的经验法则是 map() 调用中的元素需要键。
请查看此文档
https://reactjs.org/docs/lists-and-keys.html#extracting-components-with-keys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.