React - setState
import React, { Component } from 'react'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'
const root = ReactDOM.createRoot(document.getElementById('root'))
// 底层原理 - setState异步更新
// 1. setState更新是异步的
// 2. 连续调用setState更新同一个变量,会产生合并效果
// 合并:
// 最后一个setState会覆盖之前所有的setState
// 设计目的: 减少操作DOM的次数,减少性能浪费
class MyApp01 extends React.Component {
state = {
count: 0,
}
handleAdd = () => {
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 2 })
this.setState({ count: this.state.count + 3 })
console.log('this.state.count ====> count:', this.state.count) // 0
}
render() {
console.log('render is runned ... ')
const { count } = this.state
return (
<>
<div>
<h1>{count}</h1>
<button onClick={this.handleAdd}>点我我</button>
</div>
</>
)
}
}
// 底层原理 -setState第二种写法
// 语法:setState(旧的state => 新的state)
// 特点:连续调用产生合并效果
// 合并:上一次的计算结果,会传给下一次的计算参数
// 母的:减少操作DOM次数,节省性能
class MyApp02 extends React.Component {
state = {
count: 0,
}
handleAdd = () => {
// 此种写法可以将count进行合并处理
this.setState((preState) => {
return {
count: preState.count + 1,
}
})
this.setState((preState) => {
return {
count: preState.count + 2,
}
})
this.setState((preState) => {
return {
count: preState.count + 3,
}
})
console.log('this.state.count ==========> ', this.state.count) // 0
}
render() {
const { count } = this.state
return (
<>
<div>
<h1>count: {count}</h1>
<button onClick={this.handleAdd}>点我wo</button>
</div>
</>
)
}
}
// 👎💥 setState第二个参数的使用
// 1. 不会合并setState,会多次操作DOM
// 2. 容易写出回调地域
class MyApp03 extends React.Component {
state = {
count: 0,
}
handleAdd = () => {
this.setState({ count: this.state.count + 1 }, () => {
this.setState({ count: this.state.count + 2 }, () => {
this.setState({ count: this.state.count + 3 })
})
})
}
render() {
const { count } = this.state
console.log('render .....')
return (
<>
<div>
<h1>count: {count}</h1>
<button onClick={this.handleAdd}>点我我我我</button>
</div>
</>
)
}
}
const divNode = (
<div>
<MyApp03 />
</div>
)
root.render(divNode)
/*
学习目标:setState三种写法小结
步骤:
1. setState(对象) 👍
特点: 连续调用合并
合并: 覆盖效果
场景: 优先考虑
2. setState(preState => newState) 👍
特点: 连续调用合并
合并: 串联效果
场景: 第一种写法,产生覆盖效果时
3. setState(, () => {})👎
特点: 不会合并
缺点:
1. 不会产生合并效果
2. 容易写出回调地域
*/
学而不思则罔,思而不学则殆!

浙公网安备 33010602011771号