首页 > 解决方案 > 在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();
  }

但我不能用我正在生成的新值更改当前状态值。谢谢。

标签: reactjs

解决方案


setState函数不会同步更新您的值,您的状态不会立即更改。它的第二个参数允许您提供一个回调函数,当状态发生变化时触发:

  this.setState({ phone: subphone }, () => { alert(this.state.phone) //1231231234 })

推荐阅读