反应:呈现组件时在浏览器中获取运行时错误/警告
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反应:呈现组件时在浏览器中获取运行时错误/警告相关的知识,希望对你有一定的参考价值。
我正在尝试使用react为我的测试应用程序创建left hand menu like this image,并且在加载时在运行时在浏览器控制台上收到以下警告/错误。
index.js:1375 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `LeftNav`. See fb.me/react-warning-keys for more information.
in Fragment (at LeftNav.js:12)
in LeftNav (at App.js:131)
in div (at App.js:120)
in div (at App.js:118)
in div (at App.js:116)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:115)
in App (at src/index.js:7)
每个navItems道具项目都有不同的ID,因此每个组件都应该已经具有唯一的键?React.Fragment是否也应该具有唯一的密钥?LeftNav组件如下
class LeftNav extends Component {
render() {
return (
<ul>
{this.props.navItems.map((navItem) => {
return (
<React.Fragment>
<LeftNavItem key={navItem.id} navItem={navItem} menuLevel={0} />
{navItem.subMenu.map((subMenuItem) => {
return <LeftNavItem key={subMenuItem.id} navItem={subMenuItem} menuLevel={1} />
})}
</React.Fragment>
)
})}
</ul>
)
}
}
LeftNav.propTypes = {
navItems: PropTypes.array.isRequired
}
export default LeftNav;
LeftNavItem组件如下。
import React, { Component } from 'react'
import PropTypes from 'prop-types';
class LeftNavItem extends Component {
getClassName = () => {
if(this.props.menuLevel === 0) {
return 'parent_wrapper';
} else {
return '';
}
}
render() {
return (
<li className={this.getClassName()}>
<a href="">{this.props.navItem.title}</a>
</li>
)
}
}
LeftNavItem.propTypes = {
navItem: PropTypes.object.isRequired
}
export default LeftNavItem;
[LeftNav类的道具是
leftNav: [
{
id: 1,
title: 'System Admin',
active: false,
subMenu: [
{
id: 2,
title: '',
active: false
},
{
id: 3,
title: '',
active: false
},
{
id: 4,
title: '',
active: false
},
{
id: 5,
title: '',
active: false
},
{
id: 6,
title: '',
active: false
},
{
id: 7,
title: '',
active: false
},
{
id: 8,
title: '',
active: false
},
{
id: 9,
title: '',
active: false
}
]
},
{
id: 10,
title: 'Reports',
active: false,
subMenu: [
{
id: 11,
title: 'Reports',
active: false
},
{
id: 12,
title: 'Dashboard',
active: true
},
{
id: 13,
title: 'Templates',
active: false
}
]
谢谢!
答案
将密钥添加到片段中,而不是嵌套标签中。
return (
<React.Fragment key={navItem.id}>
<LeftNavItem navItem={navItem} menuLevel={0} />
{navItem.subMenu.map((subMenuItem) => {
return <LeftNavItem key={subMenuItem.id} navItem={subMenuItem} menuLevel={1} />
})}
</React.Fragment>
)
以上是关于反应:呈现组件时在浏览器中获取运行时错误/警告的主要内容,如果未能解决你的问题,请参考以下文章