React-state同步更新方式

React中一般情况下state是异步更新的,在合成事件和生命周期中一般是异步更新的,它会将几次更新状态合并在一起更新。

React同步更新方法:

一、使用回调函数:

this.setState((prevState, props) => ({
   count: prevState.count + 1
})); 

二、使用计时器:

setTimeout(() => { 
   this.changeValue(); 
}, 0);

三、使用原生事件:

componentDidMount(){    
	document.body.addEventListener('click', this.changeValue, false) 
}
changeValue = () => {    
	this.setState({counter: this.state.counter+1})  
}
发布了35 篇原创文章 · 获赞 1 · 访问量 6718

猜你喜欢

转载自blog.csdn.net/qq_36162529/article/details/102593130
今日推荐