问题:在使用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代码中直接访问。