繁体   English   中英

当给组件状态赋值时,为什么console.log 会打印之前的状态?

[英]When value is assigned to components state, why console.log prints the previous state?

我正在将数字值从 Numbers 组件发送到 Main 组件。 一切正常,直到我在我的 Main 组件中将该值设置为该组件的状态。

var Numbers = React.createClass({
    handleClick: function(number){
        this.props.num(number)
    },
    render: function(){
        return (
            <div>
                <button onClick={this.handleClick.bind(null, 1)}>1</button>
                <button onClick={this.handleClick.bind(null, 2)}>2</button>
                <button onClick={this.handleClick.bind(null, 3)}>3</button>
            </div>
        )
    }
})

var Main = React.createClass({
    getInitialState: function(){
        return {
            number: 0
        }
    },
    handleCallback: function(num){
        console.log("number is right here: " + num);
        this.setState({
            number: num
        })
        console.log("but wrong here (previous number): " + this.state.number)
    },
    render: function() {
        return (
            <Numbers num={this.handleCallback} />
            //<SomeComponent number={this.state.number} />
        )
    }
});

React.render(<Main />, document.getElementById('container'));

为什么会这样? handleCallback函数中的第二个console.log打印前一个数字,而不是num参数中的num 我需要正确的数字才能处于我的状态,因为我将立即将它作为我的SomeComponent组件中的道具发送。

https://jsfiddle.net/69z2wepo/13000/

文档

setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。 调用此方法后访问 this.state 可能会返回现有值。 无法保证对 setState 调用的同步操作,并且可能会批量调用以提高性能。

如果要在调用setState后打印更改,请使用可选的回调参数:

this.setState({
    number: num
}, function () {
    console.log(this.state.number);
});

setState 方法是异步的,因此在 console.log 调用中还没有新状态。 您可以将回调作为第二个参数传递给 setState 并在那里调用 console.log。 在这种情况下,该值将是正确的。

可能是因为在真正设置新状态之前触发了 console.log。

您应该使用该功能:

componentDidUpdate: function() {
    console.log(this.state.number);
}

每次状态更新时都会触发此函数。

希望能帮助到你

setState函数的文档中有一个有趣的注释:

setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。 调用此方法后访问 this.state 可能会返回现有值。

https://facebook.github.io/react/docs/component-api.html

为了在控制台使用打印状态号

this.setState({
        number: num
    },function(){console.log("but wrong here (previous number): " + this.state.number)})

代替

this.setState({
        number: num
    })
    console.log("but wrong here (previous number): " + this.state.number)

简而言之:使用setState(function|object nextState[, function callback])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM