网站建设预算明细表,做网站 网站违法吗,网站建设教程怎么建,wordpress博客广告代码先来思考一个老生常谈的问题#xff0c;setState是同步还是异步?
再深入思考一下#xff0c;useState是同步还是异步呢#xff1f;
我们来写几个 demo 试验一下。
先看 useState
同步和异步情况下#xff0c;连续执行两个 useState 示例
function Component() {const…先来思考一个老生常谈的问题setState是同步还是异步?
再深入思考一下useState是同步还是异步呢
我们来写几个 demo 试验一下。
先看 useState
同步和异步情况下连续执行两个 useState 示例
function Component() {const [a, setA] useState(1)const [b, setB] useState(b)console.log(render)function handleClickWithPromise() {Promise.resolve().then(() {setA((a) a 1)setB(bb)})}function handleClickWithoutPromise() {setA((a) a 1)setB(bb)}return (Fragmentbutton onClick{handleClickWithPromise}{a}-{b} 异步执行 /buttonbutton onClick{handleClickWithoutPromise}{a}-{b} 同步执行 /button/Fragment)
}结论
当点击同步执行按钮时只重新 render 了一次当点击异步执行按钮时render 了两次
同步和异步情况下连续执行两次同一个 useState 示例
function Component() {const [a, setA] useState(1)console.log(a, a)function handleClickWithPromise() {Promise.resolve().then(() {setA((a) a 1)setA((a) a 1)})}function handleClickWithoutPromise() {setA((a) a 1)setA((a) a 1)}return (Fragmentbutton onClick{handleClickWithPromise}{a} 异步执行/buttonbutton onClick{handleClickWithoutPromise}{a} 同步执行/button/Fragment)
}当点击同步执行按钮时两次 setA 都执行但合并 render 了一次打印 3当点击异步执行按钮时两次 setA 各自 render 一次分别打印 23
参考 前端进阶面试题详细解答
再看 setState
同步和异步情况下连续执行两个 setState 示例
class Component extends React.Component {constructor(props) {super(props)this.state {a: 1,b: b,}}handleClickWithPromise () {Promise.resolve().then(() {this.setState({...this.state, a: aa})this.setState({...this.state, b: bb})})}handleClickWithoutPromise () {this.setState({...this.state, a: aa})this.setState({...this.state, b: bb})}render() {console.log(render)return (Fragmentbutton onClick{this.handleClickWithPromise}异步执行/buttonbutton onClick{this.handleClickWithoutPromise}同步执行/button/Fragment)}
}当点击同步执行按钮时只重新 render 了一次当点击异步执行按钮时render 了两次
跟useState的结果一样
同步和异步情况下连续执行两次同一个 setState 示例
class Component extends React.Component {constructor(props) {super(props)this.state {a: 1,}}handleClickWithPromise () {Promise.resolve().then(() {this.setState({a: this.state.a 1})this.setState({a: this.state.a 1})})}handleClickWithoutPromise () {this.setState({a: this.state.a 1})this.setState({a: this.state.a 1})}render() {console.log(a, this.state.a)return (Fragmentbutton onClick{this.handleClickWithPromise}异步执行/buttonbutton onClick{this.handleClickWithoutPromise}同步执行/button/Fragment)}
}当点击同步执行按钮时两次 setState 合并只执行了最后一次打印 2当点击异步执行按钮时两次 setState 各自 render 一次分别打印 23
这里跟useState不同同步执行时useState也会对state进行逐个处理而setState则只会处理最后一次
为什么会有同步执行和异步执行结果不同呢
这里就涉及到 react 的 batchUpdate 机制合并更新。
首先为什么需要合并更新呢
如果没有合并更新在每次执行 useState 的时候组件都要重新 render 一次会造成无效渲染浪费时间因为最后一次渲染会覆盖掉前面所有的渲染效果。 所以 react 会把一些可以一起更新的 useState/setState 放在一起进行合并更新。
怎么进行合并更新
这里 react 用到了事务机制。 React 中的 Batch Update 是通过「Transaction」实现的。在 React 源码关于 Transaction 的部分用一大段文字及一幅字符画解释了 Transaction 的作用 * wrappers (injected at creation time)
*
* | |
* -----------------|--------|--------------
* | v | |
* | --------------- | |
* | --| wrapper1 |---|---- |
* | | --------------- v | |
* | | ------------- | |
* | | ----| wrapper2 |-------- |
* | | | ------------- | | |
* | | | | | |
* | v v v v | wrapper
* | --- --- --------- --- --- | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* -----------------|-|---|-|---|--|anyMethod|---|---|-|---|-|--------
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | --- --- --------- --- --- |
* | initialize close |
* -----------------------------------------用大白话说就是在实际的 useState/setState 前后各加了段逻辑给包了起来。只要是在同一个事务中的 setState 会进行合并注意useState不会进行state的合并处理。
为什么 setTimeout 不能进行事务操作
由于 react 的事件委托机制调用 onClick 执行的事件是处于 react 的控制范围的。
而 setTimeout 已经超出了 react 的控制范围react 无法对 setTimeout 的代码前后加上事务逻辑除非 react 重写 setTimeout。
所以当遇到 setTimeout/setInterval/Promise.then(fn)/fetch 回调/xhr 网络回调时react 都是无法控制的。
相关react 源码如下
if (executionContext NoContext) {// Flush the synchronous work now, unless were already working or inside// a batch. This is intentionally inside scheduleUpdateOnFiber instead of// scheduleCallbackForFiber to preserve the ability to schedule a callback// without immediately flushing it. We only do this for user-initiated// updates, to preserve historical behavior of legacy mode.flushSyncCallbackQueue()
}executionContext 代表了目前 react 所处的阶段而 NoContext 你可以理解为是 react 已经没活干了的状态。而 flushSyncCallbackQueue 里面就会去同步调用我们的 this.setState 也就是说会同步更新我们的 state 。所以我们知道了当 executionContext 为 NoContext 的时候我们的 setState 就是同步的 总结
我们来总结一下上述实验的结果
在正常的react的事件流里如onClick等
setState和useState是异步执行的不会立即更新state的结果多次执行setState和useState只会调用一次重新渲染render不同的是setState会进行state的合并而useState则不会
在setTimeoutPromise.then等异步事件中
setState和useState是同步执行的立即更新state的结果多次执行setState和useState每一次的执行setState和useState都会调用一次render
是不是感觉有点绕自己写一下代码体验一下就好了~