2017-03-05 38 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