我正在尝试遵循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.
我认为问题可能是我需要在做其他事情之前以某种方式清除数组,但是当这样做时,尽管它会停止错误,但选择仍然没有改变。
这是问题的jsbin
答案 0 :(得分:1)
你有this.boards
这是一个数组,每次渲染运行时都会将4个元素推到它上面。而是使用初始化为空数组的局部变量boards
。
var boards = [];
for (...) { ... };
return <div>{boards}</div>