gpt4 book ai didi

javascript - react : Encountered two children with the same key

转载 作者:行者123 更新时间:2023-11-30 00:19:38 26 4
gpt4 key购买 nike

我正在尝试学习有关 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

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

最佳答案

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

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

关于javascript - react : Encountered two children with the same key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33661059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com