[英]Warning: Each child in a list should have a unique “key” prop. Key prop doesn't show when inspect element
My ListItem.js
looks like this: 我的
ListItem.js
看起来像这样:
render() {
return(
<li key={parseInt(this.props.keyProp)}>
<button onClick={this.props.onClick}
className="sidebar__button">
{this.props.text}
</button>
</li>
);
}
When I separately place {parseInt(this.props.keyProp)}, it shows a number. 当我分别放置{parseInt(this.props.keyProp)}时,它会显示一个数字。 But when I equate it to key property of the
<li>
, I get the error Warning: Each child in a list should have a unique "key" prop.
但是,当我将其等同于
<li>
key属性时,会收到错误Warning: Each child in a list should have a unique "key" prop.
and I also cannot see any key when I inspect element on the <li>
. 而且当我检查
<li>
上的元素时,我也看不到任何键。
I am sharing the code which uses ListItem.js
我正在共享使用
ListItem.js
的代码
populateLi = () => {
let LIs = []
for (var keyItem in graphs) {
if (graphs.hasOwnProperty(keyItem)) {
LIs.push(<ListItem keyProp={keyItem} onClick={this.onClick} text={graphs[keyItem][0]["Scheme Name"]}/>)
}
}
return LIs;
}
The key
prop should be added to the function that is responsible for rendering ListItem.js
. key
道具应添加到负责渲染ListItem.js
的函数中。 So: 所以:
items.map((item) => KeyItem key={item.id} item={item} />
As per the react documentation, the "key" prop is a special string attribute that is used for optimization and identification. 根据反应文档,“键”道具是特殊的字符串属性,用于优化和识别。 It does not appear in the HTML.
它不会出现在HTML中。
The error you are getting is due to the fact that each list element does not have a unique key. 您收到的错误是由于每个列表元素都没有唯一键。 This should be fixed by assigning a unique key to each element.
应该通过为每个元素分配唯一键来解决此问题。
More info here: https://reactjs.org/docs/lists-and-keys.html 此处提供更多信息: https : //reactjs.org/docs/lists-and-keys.html
The key is supposed to be ListItem
itself not on the <li>
inside ListItem
键应该是
ListItem
本身,不在ListItem
内的<li>
LIs.push(<ListItem key={keyItem} onClick={this.onClick} text={graphs[keyItem][0]["Scheme Name"]}/>)
That fixes the problem. 这解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.