关于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:操作一致,更加简单,降低了用户的心智负担
相关推荐
Csvn15 小时前
技术选型方法论
前端
Csvn15 小时前
前端架构演进:从页面到平台的十年变革
前端
李伟_Li慢慢15 小时前
ShaderToy-山峦+蓝天+白云
前端·webgl
小码哥_常16 小时前
Android字体字重设置全攻略:XML黑科技+Kotlin动态实现,告别.ttf臃肿
前端
FYKJ_201016 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
言萧凡_CookieBoty17 小时前
AI 编程省 Token 实战:从 Spec、上下文工程到模型分层的降本策略
前端·ai编程
DFT计算杂谈17 小时前
wannier90 参数详解大全
java·前端·css·html·css3
铁皮饭盒18 小时前
第2课:5分钟!用 Trae AI 生成你的第一个后端服务(Bunjs + Elysia)
前端·后端·全栈
之歆19 小时前
DAY13_CSS3进阶完全指南 —— 背景、边框、文本、渐变、滤镜与 Web 字体(下)
前端·css·css3