react里state赋值后可以直接使用?

问题:在使用setState对state进行更新后,可以直接打印并使用吗?
样例代码:

onChange(e){

        this.preValue = e.target.value ;
        if(!/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[0-9])[0-9]{8}$/.test(this.preValue)){
            this.setState({pass: 0});
                }else{
               console.log('pass');
               this.setState({pass: 1});
              console.log(this.state.pass);
                }
  }

  
  render() {
   
        return ( 
        <div className="inputContainer">
            <input id="tel" type="tel" ref="tel" placeholder="请输入手机号码" name="phone_number" required="required" onChange={this.onChange.bind(this)} maxLength='11' />
            {this.state.pass}
        </div>
    );
    
  }

实测发现,在

<input id="tel" type="tel" ref="tel" placeholder="请输入手机号码" name="phone_number" required="required" onChange={this.onChange.bind(this)} maxLength='11' /> 
{this.state.pass}

这里的pass会实时更新,但onChange中打印的pass则是上一个状态下的值。
查阅segmentfault发现:
<blockquote>
Notes:NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.
</blockquote>
简单的说,state是异步。它存在的目的是并不仅仅是一个js中的属性,最好不要在js代码中直接访问。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容