gpt4 book ai didi

javascript - 当值被分配给组件状态时,为什么 console.log 打印以前的状态?

转载 作者:数据小太阳 更新时间:2023-10-29 04:01:54 24 4
gpt4 key购买 nike

我将数字值从 Numbers 组件发送到 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 参数中的数字。我的状态需要正确的数字,因为我将立即将其作为 Prop 发送到我的 SomeComponent 组件中。

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

最佳答案

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

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

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

关于javascript - 当值被分配给组件状态时,为什么 console.log 打印以前的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com