React的this.setState的异步问题
先看一个问题描述
import React from 'react';
export default class Home extends React.Component{
constructor(props){
super(props);
this.state={
country:""
}
}
country_search(){
console.log(this.state.country)
}
render() {
return (
<div>
<input
type="text"
placeholder={global["text"]["search_info"]}
onInput={this.country_search.bind(this)}
value={this.state.country}
onChange={(e)=>{this.setState({country:e.target.value})}}
/>
</div>
)
}
}
错误场景:onInput中console.log的时候,控制台输出的内容总比实际输入的内容少一位
错误原因:this.setState是异步执行
详解:根据js的执行代码的顺序,异步的操作会在正常js执行完之后继续执行,所以当执行到**cconsole.log()**的时候,this.state.country并没有修改,所以控制台打印总是少一位。
解决方案:
一、使用setTimeout
修改函数country_search
country_search(){
setTimeout(()=>{
console.log(this.state.country)
},0);
}
二、先保存后调用
<input
type="text"
placeholder={global["text"]["search_info"]}
onInput={this.country_search.bind(this)}
value={this.state.country}
onChange={(e)=>{ //----修改的地方
this.setState({
country:e.target.value
},() => {
console.log(this.state.country)
})
}}
/>