React.js事件需要点击2次才能执行
React.js events need 2 clicks to execute
我正在用React.js构建生命游戏,但我陷入了一种不舒服的境地:我设置为onClick={ event }
的每个事件都需要2次点击才能执行。
让我描述更多:正如你在下面的代码中所看到的,我有两个按钮(一个按钮是将板的大小更改为10 x 10,另一个是更改间隔的速度)。
一切都很好,只是当我点击这两个按钮时,我需要双击才能执行。第一次点击时,使用Chrome中的React Developer Tool,我可以看到包括width, height, speed
在内的状态发生了变化,但board
的状态仍然保持不变。只有在第二次单击之后,board
状态才会发生更改。
有人能解释为什么并告诉我如何修复吗?谢谢
这是我的代码的一部分
var GameBoard = React.createClass({
getInitialState: function() {
return {
width: 10,
height: 10,
board: [],
speed: 1000,
};
},
// clear the board to the initial state
clear: function(width, height) {
this.setState({
width: width,
height: height,
});
this.setSize();
clearInterval(this.game);
},
// set the size of the board
setSize: function() {
var board = [];
for (var i = 0; i < this.state.height; ++i) {
var line = [];
for (var j = 0; j < this.state.width; ++j)
line.push(0);
board.push(line);
}
this.setState({
board: board
});
},
// start the game
start: function() {
this.game = setInterval(this.gameOfLife, this.state.speed);
},
gameOfLife: function() { // game of life },
// change the speed of the game
changeSpeed: function(speed) {
this.setState({ speed: speed });
clearInterval(this.game);
this.start();
},
// change the size to 10 x 10
smallSize: function() {
this.clear(10, 10);
},
render: function() {
return (
<div className="game-board">
<h1>Conway's Game of Life</h1>
<h2>Generation: { this.state.generation }</h2>
<div className="control">
<button className="btn btn-default" onClick={ this.start }>Start</button>
</div>
<Environment board={ this.state.board } onChangeSquare = { this.onChangeSquare }/>
<div className="size">
<h2>Size</h2>
<button className="btn btn-default" onClick={ this.smallSize }>Small (10 x 10)</button>
</div>
<div className="speed">
<h2>Speed</h2>
<button className="btn btn-default" onClick={ this.changeSpeed.bind(this, 900) }>Slow</button>
</div>
</div>
)
}
});
原因是组件的状态不会立即改变。
在clear()方法中,您可以设置宽度和高度状态。但在内部,当它们对setSize()方法做出反应时,它们不会立即更新。它们只有在到达渲染方法时才会更新。
当您第二次单击该按钮时,状态将正确更新。这就是为什么它在二审中有效。
一个解决方案是,请不要保留国家在道具中使用的宽度和高度。将10*10保留为separete默认道具,并在setSize方法中使用它。
相关文章:
- 设置第一次执行的超时
- 函数不会(正确)多次执行
- Javascript-防止函数多次执行
- JS - 在函数内时多次执行键
- IE8在第一次执行后未运行javascript
- 多次执行脚本的 jQuery
- 如何循环函数数组并在单击时一次执行一个
- 在没有javascript循环的情况下多次执行命令
- 如何在不刷新页面的情况下多次执行构造函数
- RequireJS:模块函数是每次导入模块时执行还是第一次执行
- 如何多次执行捕获组
- 多次执行 AJAX 请求时删除以前的数据
- 我的HTML5 / Javascript代码不会多次执行相同的功能
- Firefox SDK 多次执行请求
- Javascript 多次执行 onload “GET” 方法
- 出于性能原因,我是否应该避免多次执行相同的函数声明
- 如果脚本在第一次尝试时失败,请第二次执行脚本
- 在angularjs中两次执行控制器的routeparams中的特殊字符
- AngularJS在控制器中多次执行jquery
- 使用不同的变量值多次执行外部javascript文件中的$(document).ready()中的代码