2017-03-05 3 views
1

これは私のモデルである:状態で、最近設定されたプロパティにアクセスすると、以前の値を返します

class Board extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     squares: Array(3).fill(Array(3).fill(null)), 
     xIsNext: true 
    }; 
    } 

    get turn() { 
    return this.state.xIsNext ? 'X' : 'O'; 
    } 

    handleTurn(x, y) { 
    const squares = this.state.squares.slice().map(function(row) { 
     return row.slice(); 
    }); 

    const turn = this.turn; // this returns either "X" or "Y" 
    squares[x][y] = turn; // this is the value I'm going to be accessing later on 
    this.setState({ 
     squares: squares 
    }); 

    if (this.isSolved(x, y)) { 
     console.log('VICTORY!') 
    } 
    this.nextPlayer(); 
    } 
    isSolved(x, y) { 
    var count = 0 
    var player = this.state.squares[x][y]; // here is when I try to access the value set at at 'handleTurn') 
    // more stuff down there 
    return false; 
} 

私の問題はこれです:isSolvedhandleTurnから呼び出され、handleTurnに私からの座標のいずれかを設定します二次元で 'X'または 'Y'のいずれかになります。しかし、その値をisSolvedにチェックすると、私はちょうど設定した値ではなく、の前のの値を取得します。

例えば、最初の呼び出しにnull(私はXを期待する場合)、2回目の呼び出しを取得し、(私はそれまでにOを期待するとき)私はなど

答えて

4

ではsetStateworks (mostly) asynchronously反応し、Xを取得します1回のパスで複数の変更をバッチすることができます。

つまり、this.setStatehandleTurnにある場合、実際には状態はまだ変更されていません。

setStateには、状態が実際に変更されたときに実行するコールバック関数である2番目の引数を渡すことができます。 https://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm

+0

グレート:

はここsetStateの行動に、より深みに入る興味深い記事です!ありがとう。今私はドキュメントでそれを見つける。 :) – yivi

関連する問題