将值分配给组件状态时,为什么console.log会打印以前的状态? [英] When value is assigned to components state, why console.log prints the previous state?

查看:109
本文介绍了将值分配给组件状态时,为什么console.log会打印以前的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sending values of numbers from Numbers component to Main component. Everything is working fine until I set that value in my Main component to that component's state.

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 参数。我需要正确的号码才能进入我的状态,因为我将立即将其作为道具发送到我的 SomeComponent 组件中。

Why is it behaving like this? Second console.log in handleCallback function prints the previous number, not the number which is in num parameter. I need right number to be in my state, because I'm going to send it immediately as an props in my SomeComponent component.

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

推荐答案

来自 docs


setState()不会立即改变this.state但会创建
待定状态转换。调用此
方法后访问this.state可能会返回现有值。对于调用setState的同步操作没有
保证,并且可以为了性能增益调用
批次。

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

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

If you want to print the change after a call to setState, use the optional callback parameter:

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

这篇关于将值分配给组件状态时,为什么console.log会打印以前的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆