首页 > 解决方案 > 反应 setState 得到错误的状态

问题描述

我最近开始学习 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')
);

这些代码将开始为:

然后它显示:

毫无疑问,号码已经传入,但似乎没有从最后得到this.state.number

我期望的是输出:

这个问题的原因是什么?谢谢。

标签: reactjsstatus

解决方案


setStateasync,更新状态需要时间。使用回调in setState,它将在执行setState完成时执行。

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

演示


推荐阅读