问题描述
我正在将数字值从 Numbers 组件发送到 Main 组件.在我将 Main 组件中的该值设置为该组件的状态之前,一切正常.
var Numbers = React.createClass({处理点击:函数(数字){this.props.num(数字)},渲染:函数(){返回 (<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({获取初始状态:函数(){返回 {数量:0}},处理回调:函数(编号){console.log("数字就在这里:" + num);这个.setState({数:数})console.log("但是这里错了(前一个数字):" + this.state.number)},渲染:函数(){返回 (<数字 num={this.handleCallback}/>//<SomeComponent number={this.state.number}/>)}});React.render(<Main/>, document.getElementById('container'));为什么会这样?handleCallback
函数中的第二个 console.log
打印前一个数字,而不是 num
参数中的数字.我需要正确的数字才能处于我的状态,因为我将立即将其作为 SomeComponent
组件中的道具发送.
https://jsfiddle.net/69z2wepo/13000/
解决方案 来自 文档:
setState() 不会立即改变 this.state 而是创建一个等待状态转换.调用 this 后访问 this.state方法可能会返回现有值.没有保证对 setState 的调用和调用的同步操作可能进行批处理以获得性能提升.
如果要在调用 setState
后打印更改,请使用可选的回调参数:
this.setState({数:数}, 功能 () {控制台.log(this.state.number);});
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'));
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/
解决方案 From the docs:
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 会打印以前的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-26 07:45