React:遇到两个 children 具有相同的键

React: Encountered two children with the same key

我正在尝试学习有关 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, `.[=12=]`. 
Child keys must be unique; when two children share a key, only the first child will be used. 

我认为问题可能是我需要在做任何其他事情之前以某种方式清除数组,但是当这样做时,虽然它停止了错误,但选择仍然没有改变。

这是问题的jsbin

http://jsbin.com/hakisoyuli/1/edit?js,console,output

你有 this.boards 这是一个数组,每次渲染运行时都会将 4 个元素推到它上面。而是使用初始化为空数组的局部变量 boards

var boards = [];
for (...) { ... };
return <div>{boards}</div>