1
我正在嘗試關注React的一個教程,練習的一部分是使用狀態來構建我自己的循環盒組件,以切換選擇哪個盒子。我已經把我的代碼像這樣反應:遇到兩個孩子使用相同的密鑰
var Board = React.createClass({
render: function() {
var className = "board";
if (this.props.selected) {
className += " selected";
}
return (< div className = {
className
} > {
this.props.index + 1
} < /div>
);
}
});
var BoardSwitcher = React.createClass({
boards: [],
toggleStateSelection: function() {
var self = this;
this.setState({
selected: function(){
if (self.state.selected + 1 < self.boards.length) {
return self.state.selected + 1;
} else {
return 0;
}
}()
})
},
getInitialState: function() {
return {
selected: 0
}
},
render: function() {
for (var ii = 0; ii < this.props.numBoards; ii++) {
var isSelected = ii === this.state.selected;
this.boards.push(
<Board index={ii} selected={isSelected} key={ii}/>);
}
return (<div>
< div className = "boards" > {
this.boards
} < /div>
<button onClick={this.toggleStateSelection}>Toggle</button >
< /div>
);
}
});
React.render(
<BoardSwitcher numBoards={4}/> ,
document.body
);
但我不斷收到錯誤
Warning: flattenChildren(...): Encountered two children with the same key, `.$0`.
Child keys must be unique; when two children share a key, only the first child will be used.
我認爲這個問題可能是我之前需要以某種方式清除陣列我做了其他任何事情,但是在做這件事時,儘管它會阻止錯誤,但選擇仍然不會改變。
這裏的問題是
http://jsbin.com/hakisoyuli/1/edit?js,console,output