2017-03-05 33 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),第二個電話,我會得到X(當我期望O那時)等

回答

4

在陣營setStateworks (mostly) asynchronously以便能夠一次批量處理多個更改。

也就是說,當你this.setStatehandleTurn的狀態還沒有真正改變呢。

您可以傳遞setState第二個參數,這是您想要在狀態實際更改時執行的回調函數。

這裏有一個有趣的文章,其進入更深入的setState行爲:https://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm

+0

太好了!謝謝。現在我在文檔中找到它。 :) – yivi