我正在尝试使用react.js在我的Meteor.js应用程序中设置动态菜单。每次我运行这个,我都会得到"键"错误。发生了什么事?
SocialMenu.jsx:
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>
);
}
});
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')
);
});
}
另外,就最佳实践而言,我应该在启动函数中为每个React类运行render函数吗?谢谢。
答案 0 :(得分:2)
抱怨的是你没有为孩子指定一个密钥,所以请创建一个唯一的密钥,如果对象是相同的,密钥应该是相同的:
<li key={uniqueKey} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;