![](/img/trans.png)
[英]Getting warning “Warning: Each child in a list should have a unique ”key“ prop.” when my component render
[英]Warning: Each child in a list should have a unique “key” prop. Key prop doesn't show when inspect element
我的ListItem.js
看起來像這樣:
render() {
return(
<li key={parseInt(this.props.keyProp)}>
<button onClick={this.props.onClick}
className="sidebar__button">
{this.props.text}
</button>
</li>
);
}
當我分別放置{parseInt(this.props.keyProp)}時,它會顯示一個數字。 但是,當我將其等同於<li>
key屬性時,會收到錯誤Warning: Each child in a list should have a unique "key" prop.
而且當我檢查<li>
上的元素時,我也看不到任何鍵。
我正在共享使用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;
}
key
道具應添加到負責渲染ListItem.js
的函數中。 所以:
items.map((item) => KeyItem key={item.id} item={item} />
根據反應文檔,“鍵”道具是特殊的字符串屬性,用於優化和識別。 它不會出現在HTML中。
您收到的錯誤是由於每個列表元素都沒有唯一鍵。 應該通過為每個元素分配唯一鍵來解決此問題。
此處提供更多信息: https : //reactjs.org/docs/lists-and-keys.html
鍵應該是ListItem
本身,不在ListItem
內的<li>
LIs.push(<ListItem key={keyItem} onClick={this.onClick} text={graphs[keyItem][0]["Scheme Name"]}/>)
這解決了問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.