reactjs - 反应 setState 得到错误的状态
问题描述
我最近开始学习 React,这是我发现的一个问题。我在这里尝试做的是:
- 将数字设置为 0 作为初始状态。
- 用我传入的数字改变状态。
- 再次打印状态。
这是代码:
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
这个问题的原因是什么?谢谢。
解决方案
推荐阅读
- javascript - 将下载 url 分配给变量 firestore
- python - 将列表中的值输入到 Pandas 数据框中
- asp.net-core - 在按钮单击 Mvc Core 时传递模型子集
- assembly - 添加后的意外行为
- c++ - 为什么使用 getline 后 cin 没有获取缓冲区数据?
- javascript - 尝试运行一个导入失败的笑话测试,可能与猫鼬有关
- amazon-web-services - 使用每个 terraform 在单独的 AZ 中创建不同的 EC2 实例
- snowflake-cloud-data-platform - 列出雪花中特定表中具有数据类型的所有列
- c++ - 从 std::vector 复制到推力::device_vector 时出现未处理的异常
- php - 在 WooCommerce 结帐中为特定产品类别制作所需的订单注释