关于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:操作一致,更加简单,降低了用户的心智负担
相关推荐
kyriewen117 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
摇滚侠8 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
Timer@8 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫8 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81639 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan10 小时前
FastAPI -API Router的应用
前端·网络·python
走粥11 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory00111 小时前
layui select重新渲染
前端·layui
weixin1997010801612 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化