我正在使用一个map函数根据一系列对象创建一个游戏板,然后单击setState以使游戏发生。我可以成功更新状态,但是在执行其他操作之前视图不会更新。我猜测问题出在map函数如何将props传递给子元素(Cell),但我无法弄清楚自己在做什么错。
var board = [];
var width = 50;
var height = 30;
var size = width * height;
for (var i=1; i<=size; i++) {
board[i] = {id: i, status: 'dead'};
}
var Cell = React.createClass({
turn: function() {
this.props.turn(this.props.id);
},
render: function() {
return <div id={this.props.id} className={this.props.status} onClick={this.turn}></div>
}
});
var GameBoard = React.createClass({
getInitialState: function() {
return {
board: board
};
},
handleClick: function(id) {
var newBoard = this.state.board;
newBoard[id] = {id: id, status: 'alive'};
this.setState({board: newBoard});
},
move: function() {
var board = this.state.board;
var newBoard = board;
for (var j=1;j<=board.length;j++) {
if (board[j].status == 'alive') {
newBoard[j-1] = {id: j-1, status: 'alive'};
newBoard[j] = {id: j, status: 'dead'};
}
}
this.setState({board: newBoard});
},
render: function() {
var squares = this.state.board.map(function(item){
return <Cell id={item.id} status={item.status} turn={this.handleClick}/>
}.bind(this));
return (
<div>
<h1>Game of Life</h1>
<button className="btn btn-default" onClick={this.move}>Run</button>
<div className='boardContainer'>{squares}</div>
</div>
);
}
});
ReactDOM.render(<GameBoard/>,document.getElementById('app'));
move
函数中的循环是一对一的,因此在到达时会引发错误setState
。方法的前两行仅this.state.board
在变量中分配对的引用newBoard
。因此,您是在“更新”状态,但不能使用正确地进行状态更新setState
。这就是为什么在你的下一个点击,它调用板更新setState
在handleClick
。
1)您应该修改状态的深层副本,而不是状态本身
2)修复for循环中的一一错误
var board = this.state.board;
var newBoard = board; // Note, this is a reference to this.state.board. That's bad!
for (var j=1; j<=board.length - 1; j++) { // note, -1
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句