关于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:操作一致,更加简单,降低了用户的心智负担
相关推荐
IT_陈寒2 小时前
SpringBoot这个自动配置坑我跳了三次
前端·人工智能·后端
kyriewen2 小时前
我用 AI 一周写完了整个项目,上线第一天就崩了——这是我踩过最贵的 5 个坑
前端·javascript·ai编程
Larcher3 小时前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
默_笙3 小时前
🃏 JS 只有 8 种数据类型,但我花了 2 天才搞懂 null 和 undefined 的区别
javascript
牧艺3 小时前
从零到协同:构建类飞书在线文档系统的五个技术重难点
前端·人工智能
jump_jump3 小时前
流式 HTML:从 htmx 片段装配到浏览器原生增量渲染
javascript·性能优化·前端工程化
红尘散仙3 小时前
想写一个像样的终端 App?试试把 React 的开发体验搬进 Rust TUI
前端·rust
袋鼠云数栈UED团队4 小时前
一套 Spec-First 的 AI 编程工作流
前端·人工智能
袋鼠云数栈前端4 小时前
一套 Spec-First 的 AI 编程工作流
前端·ai+
angerdream4 小时前
Android手把手编写儿童手机远程监控App之vue3 路由守卫
前端