关于React的setState

不可变值

state必须在构造函数中定义

在setState之前不能修改state的值,不要直接修改state,使用不可变值


可能是异步更新

  • 直接使用时异步的
javascript 复制代码
this.setState({
	count: this.state.count + 1
}, () => {
	console.log('count by callback', this.state.count) // 回调函数
})
console.log('count', this.state.count) // 异步的,拿不到最新值
  • 在setTimeout中setState是同步的
javascript 复制代码
setTimeout(() => {
	this.setState({
		count: this.state.count + 1
	})
	console.log('count', this.state.count) // 在settimeout中打印值正确
}, 0)
  • 自己定义的DOM事件,setState是同步的
javascript 复制代码
clickHandler = () => {
	this.setState({
		count: this.state.count + 1
	})
	console.log('count in body event', this.state.count);
}
componentDidMount() {
	document.body.addEventListener('click', this.clickHandler)
}

componentWillUnmount() {
	document.body.removeEventListener('click', this.clickHandler)
}

可能被合并

如下例子

  • 直接使用 - 传入对象会合并
javascript 复制代码
this.setState({
	count: this.state.count + 1
})
this.setState({
	count: this.state.count + 1
})
this.setState({
	count: this.state.count + 1
})

console.log(this.state.count) // 1
  • 传入函数 - 函数不能被合并
javascript 复制代码
this.setState((prevState, props) => {
	return {
		count: prevState.count + 1
	}
})
this.setState((prevState, props) => {
	return {
		count: prevState.count + 1
	}
})
this.setState((prevState, props) => {
	return {
		count: prevState.count + 1
	}
})
console.log(this.state.count) // 3

React18

  • React组件事件:异步更新+合并state
  • DOM事件,setTimeout:异步更新+合并state
  • Automatic Batching 自动批处理

总结

  • React <= 17:只有React组件事件才批处理
  • React18: 所有事件都自动批处理 Automatic Batching
  • React18:操作一致,更加简单,降低了用户的心智负担
相关推荐
CHANG_THE_WORLD1 分钟前
PDF文档结构分析 一
前端·pdf
2601_9498333912 分钟前
flutter_for_openharmony口腔护理app实战+知识实现
android·javascript·flutter
东东51617 分钟前
果园预售系统的设计与实现spingboot+vue
前端·javascript·vue.js·spring boot·个人开发
rainbow688918 分钟前
Python学生管理系统:JSON持久化实战
java·前端·python
打小就很皮...22 分钟前
React Router 7 全局路由保护
前端·react.js·router
起风的蛋挞31 分钟前
Matlab提示词语法
前端·javascript·matlab
有味道的男人32 分钟前
1688获得商品类目调取商品榜单
java·前端·spring
txwtech38 分钟前
第20篇esp32s3小智设置横屏
前端·html
Exquisite.1 小时前
企业高性能web服务器---Nginx(2)
服务器·前端·nginx
怪兽毕设1 小时前
基于SpringBoot的选课调查系统
java·vue.js·spring boot·后端·node.js·选课调查系统