警告:数组或迭代器中的每个子级都应具有唯一的;“关键”;道具检查“SocialMenu”的渲染方法。(Meteor.js应用程序中的React.js)
我正在尝试使用react.js在Meteor.js应用程序中设置动态菜单。每次我运行它时,都会出现“key”错误。发生了什么事 SocialMenu.jsx:警告:数组或迭代器中的每个子级都应具有唯一的;“关键”;道具检查“SocialMenu”的渲染方法。(Meteor.js应用程序中的React.js),meteor,reactjs,Meteor,Reactjs,我正在尝试使用react.js在Meteor.js应用程序中设置动态菜单。每次我运行它时,都会出现“key”错误。发生了什么事 SocialMenu.jsx: SocialMenu = React.createClass({ getInitialState: function(){ return { focused: 0 }; }, clicked: function(index){ // The click handler will
SocialMenu = React.createClass({
getInitialState: function(){
return { focused: 0 };
},
clicked: function(index){
// The click handler will update the state with
// the index of the focused menu entry
this.setState({focused: index});
},
render: function() {
// Here we will read the items property, which was passed
// as an attribute when the component was created
var self = this;
// The map method will loop over the array of menu entries,
// and will return a new array with <li> elements.
return (
<div>
<ul>{ this.props.items.map(function(m, index){
var style = '';
if(self.state.focused == index){
style = 'focused';
}
// Notice the use of the bind() method. It makes the
// index available to the clicked function:
return <li className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;
}) }
</ul>
<p>Selected: {this.props.items[this.state.focused]}</p>
</div>
);
}
});
SocialMenu=React.createClass({
getInitialState:函数(){
返回{聚焦:0};
},
单击:函数(索引){
//单击处理程序将使用更新状态
//焦点菜单项的索引
this.setState({focused:index});
},
render:function(){
//这里我们将读取传递的items属性
//作为创建组件时的属性
var self=这个;
//map方法将在菜单项数组上循环,
//并将返回一个包含元素的新数组。
返回(
{this.props.items.map(函数(m,索引){
var样式=“”;
if(self.state.focused==索引){
风格=‘专注’;
}
//注意bind()方法的使用
//可用于单击功能的索引:
return- {m}
;
}) }
所选:{this.props.items[this.state.focused]}
);
}
});
myapp.jsx:
if (Meteor.isClient) {
Meteor.startup(function () {
// Use Meteor.startup to render the component after the page is ready
ReactDOM.render(<App />, document.getElementById("render-target"));
ReactDOM.render(
<SocialMenu items={ ['Home', 'Services', 'About', 'Contact us'] } />,
document.getElementById('socialmenu')
);
});
}
if(Meteor.isClient){
Meteor.startup(函数(){
//在页面准备就绪后,使用Meteor.startup呈现组件
ReactDOM.render(,document.getElementById(“呈现目标”);
ReactDOM.render(
,
document.getElementById('socialmenu')
);
});
}
另外,就最佳实践而言,我是否应该在启动函数中为每个React类运行render函数?谢谢 react抱怨的是您没有为子项指定密钥,因此请创建唯一密钥,如果对象相同,则密钥应相同:
<li key={uniqueKey} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;
{m} ;
很抱歉,我是新手,我应该在uniqueKey变量中添加什么?在映射函数中,您可以尝试如下操作:return键
,则它只能更新需要更新的键。否则它可以正常工作,但在大型列表上性能较差。希望这有帮助!(对于官方文件:)