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

后端 未结 5 1341
死守一世寂寞
死守一世寂寞 2020-11-30 09:26

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.<

相关标签:
5条回答
  • 2020-11-30 09:28

    Probably because the console.log is triggered before the new state has been really set.

    You should use the function:

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

    This function is triggered each time the state is updated.

    Hope it helps

    0 讨论(0)
  • 2020-11-30 09:33

    In order to print state number in console use

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

    instead of

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

    In short: use setState(function|object nextState[, function callback])

    0 讨论(0)
  • 2020-11-30 09:41

    From the docs:

    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.

    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);
    });
    
    0 讨论(0)
  • 2020-11-30 09:48

    The setState method is asynchronous, so the new state is not there yet on console.log call. You can pass a callback as a second parameter to setState and call console.log there. In this case the value will be correct.

    0 讨论(0)
  • 2020-11-30 09:50

    In the docs of the setState function is an interesting note:

    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.

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

    0 讨论(0)
提交回复
热议问题