我正在使用反应电话输入库之一,并且电话号码的值为“ +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();
}
但是我无法用我正在生成的新值更改当前状态值。谢谢。
答案 0 :(得分:4)
setState
函数不会同步更新您的值,不会立即更改您的状态。它的第二个参数允许您提供状态改变后触发的回调函数:
this.setState({ phone: subphone }, () => { alert(this.state.phone) //1231231234 })