关于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:操作一致,更加简单,降低了用户的心智负担
相关推荐
万少6 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站8 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名10 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫11 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊11 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter11 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折11 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_11 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码111 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial11 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js