javascript - setState 是否需要一些时间来执行?

标签 javascript reactjs ecmascript-6

<分区>

我正在关注 React 网站上的一些教程,并尝试了一些示例代码。这是 codepen 中该代码的链接

https://codepen.io/gaearon/pen/gWWZgR?editors=0010

handleClick(i) {
        const history = this.state.history.slice(0, this.state.stepNumber + 1);
        const current = history[history.length - 1];
        const squares = current.squares.slice();
        if (calculateWinner(squares) || squares[i]) {
            return;
        }
        squares[i] = this.state.xIsNext ? "X" : "O";
        this.setState({
            history: history.concat([{
                squares: squares,
            }]),
            stepNumber: history.length,
            xIsNext: !this.state.xIsNext,
        });
        console.log(this.state.history);
    }

render() {
        console.log(this.state.history);
        const history = this.state.history;
        const current = history[this.state.stepNumber];
        const winner = calculateWinner(current.squares);

        const moves = history.map((val, index) => {
            const desc = index ? 'Go to move #' + index : 'Go to game start';
            return (
                <li key={index}>
                    <button onClick={() => this.jumpTo(index)}>{desc}</button>
                </li>
            );
        });

        let status;
        if (winner) {
            status = 'Winner: ' + winner;
        } else {
            status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
        }

        return (
            <div className="game">
                <div className="game-board">
                    <Board
                        squares={current.squares}
                        onClick={(i) => this.handleClick(i)}
                    />
                </div>
                <div className="game-info">
                    <div>{status}</div>
                    <ol>{moves}</ol>
                </div>
            </div>
        );
    }

我的问题是

console.log

在 handleClick 方法和

console.log

在 render 方法中显示了 2 个不同的答案。但它们应该显示出与我理解的相同,因为 handleClick 的 console.log 是在设置状态之后。是因为set State需要一些时间吗?或任何其他事情?

最佳答案

setState 函数是异步的。如果你想在状态更新后记录日志,你需要像这样在 setState 回调中调用 console.log:

this.setState({
    history: history.concat([{
        squares: squares,
    }]),
    stepNumber: history.length,
    xIsNext: !this.state.xIsNext,
}, () => {
    console.log(this.state.history);
});

希望这有帮助:)

关于javascript - setState 是否需要一些时间来执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53178922/

相关文章:

javascript - 流 clearTimeout 与 TimeoutID 不兼容

reactjs - 如何在滚动上 react konva 缩放

javascript - ECMAScript v 6 何时成为标准

javascript - Sys.WebForms.PageRequestManagerServerErrorException 回发时

javascript - 错误:无法在“节点”上执行“appendChild”:参数1不是“节点”类型

javascript - Window.load 仅在浏览器选项卡更改后有效

javascript - react 通用容器与深层 child 的沟通

javascript - 重用 react 组件

eclipse - 有没有办法在 Eclipse IDE 中开发 react ?

javascript - ECMAScript 6 中 "extending"原型(prototype)的语法