React.js 事件需要点击 2 次才能执行

IT技术 javascript reactjs onclick
2021-05-04 12:43:26

我正在通过 React.js 构建生命游戏,但我陷入了一种不舒服的境地:我设置的每个事件都onClick={ event }需要点击 2 次才能执行。

我再详细说明一下: 正如你在我下面的代码中看到的,我有 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>
        )
    }
});
1个回答

原因是组件的状态不会立即改变。

在 clear() 方法中,您设置宽度和高度状态。但是在内部,当他们对 setSize() 方法做出react时,他们不会立即更新。它们只会在到达渲染方法时更新。

当您第二次单击该按钮时,状态将被正确更新。这就是它在第二个实例中起作用的原因。

一种解决方案请不要保留宽度和高度,因为状态在props中使用它。保持 10 * 10 作为单独的默认属性并在 setSize 方法中使用它。