繁体   English   中英

反应setState获取错误状态

[英]react setState get wrong status

我最近开始学习React,这是我发现的一个问题。 我在这里尝试做的是:

  1. 将数字设置为0作为初始状态。
  2. 用我传入的号码更改状态。
  3. 再次打印状态。

这是代码:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number:0,
    };
  }

 changeNum(num){
    console.log('num pass in is: '+num);
    console.log('before, the num is: ' + this.state.number);
    this.setState({number: num});
    console.log('now the point chosen is: ' + this.state.number);
 }

  render() {
    return (
      <button onClick={()=>this.changeNum(1)}>Click</button>
    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById('root')
);

这些代码的开头为:

  • 传入的数字是:1
  • 之前的数字是:0
  • 现在选择的点是:0

然后它显示:

  • 传入的数字是:1
  • 之前的数字是:1
  • 现在选择的点是:1

毫无疑问,这个数字已经传递了,但是似乎不是从上一个this.state.number

我期望的是输出:

  • 传入的数字是:1
  • 之前的数字是:0
  • 现在选择的点是:1

此问题的原因是什么? 谢谢。

setStateasync ,需要花费一些时间来更新状态。 setState使用回调 ,该回调将在setState完成执行时执行。

this.setState({
   number: num
}, () => console.log('now the point chosen is: ' + this.state.number));

演示

建议使用prevState设置状态。

this.setState(prevState => ({
 num: prevState.number = num,
})).

暂无
暂无

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

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