reactjs - 在reactjs中提交之前无法更改状态值
问题描述
我正在使用反应电话输入库之一,并获取电话号码的值是“+9901231231234”格式。我只希望最后十个值是整数形式。所以我正在将它们转换为数字。
if (this.validator.allValid()) {
const phnNo = this.state.phone // +9901231231234
if(phnNo.length>10){
var lastTen = phnNo.substr(phnNo.length - 10);
const subphone = Number(lastTen) //1231231234
this.setState({ phone: subphone }) // Now I want to set the this.state.phone = 1231231234
alert(this.state.phone) // +9901231231234
}
} else {
this.validator.showMessages();
// rerender to show messages for the first time
// you can use the autoForceUpdate option to do this automatically`
this.forceUpdate();
}
但我不能用我正在生成的新值更改当前状态值。谢谢。
解决方案
该setState
函数不会同步更新您的值,您的状态不会立即更改。它的第二个参数允许您提供一个回调函数,当状态发生变化时触发:
this.setState({ phone: subphone }, () => { alert(this.state.phone) //1231231234 })
推荐阅读
- php - 致命错误:对 SQL SERVER 2012 的非对象 XAMPP 上的成员函数 query() 调用
- python - 如何在熊猫数据框中的每个组上标记第一个值
- parallax.js - 视差不滚动
- javascript - 我想用 exec() 函数在我的 php 文件中运行 javascript 文件,但它出现了错误消息,我该如何解决?
- powershell - 使用 Get-Content cmdlet 读取 1000 行 (350KB) XML 文件需要 3 分钟
- r - 在 Shiny 中更新复选框值
- javascript - 如何使用 Map() 返回承诺数据
- css - 如何从垫选择下拉输入中删除动画
- r - OpenAPI 生成的 R 枚举有问题并且似乎什么都不包含
- postgresql - 休眠地图列表
到 Postgres 枚举