問題:在使用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>
);
}
實測發(fā)現(xiàn)弃酌,在
<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則是上一個狀態(tài)下的值儡炼。
查閱segmentfault發(fā)現(xiàn):
<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代碼中直接訪問多柑。