2016-04-16 82 views
5

我正在通過React.js構建生命遊戲,並陷入一個不舒服的境地: 我設置爲onClick={ event }的每個事件都需要點擊2次來執行。React.js事件需要2次點擊才能執行

讓我描述更多: 正如你可以在下面我的代碼看,我有2個按鈕(一個鍵是電路板的尺寸變更爲10×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> 
     ) 
    } 
}); 
+0

嗯,不確定。但是,你不需要在'onClick'處理程序中'綁定'使用'this'的所有函數嗎?例如'smallSize' –

+0

通過'smallSize'使用'bind'是什麼意思?我認爲這種方法很好,只是'onClick'的效果不起作用。 – pexea12

+0

即使第二個函數似乎在其實現中使用了this,this.clear.bind(this)'this.smallSize.bind(this)'''this.clear(10,10) ')。它不應該導致你所看到的問題,但它對我來說似乎有點奇怪 –

回答

0

一部分的原因是組件的狀態不會立即更改。

在clear()方法中,設置寬度和高度狀態。但在內部,當他們反應setSize()方法時,他們不會立即更新。只有當它們到達渲染方法時,它們纔會更新。

當您第二次單擊該按鈕時,狀態將被正確更新。這就是爲什麼它在第二種情況下工作。

一個解決方案,請不要保持寬度和高度作爲國家在道具中使用它。保留10 * 10作爲獨立的默認道具,並在setSize方法中使用它。

相關問題