组件从 React 中落后一步更新状态

时间:2021-04-14 06:08:44

标签: javascript reactjs setstate

我正在尝试更新游戏数据,但它后来居上。我想我应该以不同的方式调用 this.setState({}),但有人可以帮我这样做吗?

代码如下:

    handleMove(cords) {
        // Return if the game is already over
        if (this.state.winner) {
            return
        }

        // This should be the copy of the this.state.history till the end
        const history = this.state.history.slice();
        const current = history[history.length - 1];

        // Cords parameter is an array of coordinates of squares whose values are
        //to be changed or passed in
        const color = this.state.blackIsNext ? "black" : "white";
        // Here, I create a new squares array, states of each squares
        //one-by-one are added, which will be immutably pushed inside the new history
        //array
        const nextSquares = current.squares.map((row, y) =>
            row.map((square, x) =>
                // find if this [x,y] is in the cords array and replace it if it is
                cords.some((cord) => cord[0] === y && cord[1] === x) ? color : square
            )
        );
        
        // Create the new history element, element's state.history
        //value will be this new one
        const newHist = history.concat({squares: nextSquares})
        this.setState({
            history: newHist,
            stepNumber: history.length,
        });
        

如果此代码不足以给您提示,请告诉我。非常感谢。

1 个答案:

答案 0 :(得分:0)

解决了好几天,终于搞定了。我在 setState 回调中调用了一部分代码,最初是在我调用 setState 之后。像这样:

handleMove(cords) {
        // You'll return if the game is already over or the value of the square is NOT null
        if (this.state.winner) {
            return
        }
        // Handle the recently made move here
        const history = [...this.state.history];
        const squares = history[history.length - 1].slice();
        // Handle click
        const color = this.state.blackIsNext ? "black" : "white";
        const nextSquares = squares.map((row, y) =>
            row.map((square, x) =>
                cords.some((cord) => cord[0] === y && cord[1] === x) ? color : square
            )
        );
        //console.log(this.state.history)
        const newHist = history.concat([nextSquares])
        return newHist
    }

然后:

const upcoming = this.handleMove(turning)
this.setState({
    history: upcoming,
    stepNumber: upcoming.length - 1
},() => {
    // My function that is affected by setState
    this.setWinnerAndTurn(this.state.history)
    console.log(this.state.history)
})

经过我所有的研究,从同步调用 setState 到 setTimeOut(),我相信这是(迄今为止)处理 setState 更新的最简单方法。