setState的多种用法,辨别异步还是同步,有源码翻译

在初学时,一直认为setState是异步的,看完网上的文章后,才知道这是个伪异步,在源码中能猜出来他的底层实现原理

/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together.  You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*/

/**
* 翻译如下:
* 设置状态的子集。总是使用这个来改变状态。你应该认为"this.state"是不可变的。
* 没有人能保证"this.state"将立即更新,因此访问"this.state"调用此方法后可能返回旧值。
* 
* 无法保证对“setState”的调用会同步运行,因为它们最终可能会被批处理在一起。
* 您可以提供一个可选的回调,它将在对setState的调用实际完成时执行。
* 
* 当一个函数被提供给setState时,它将在将来的某个时候被调用(不同步)。
* 它将与最新(up-to-date)组件参数(state、props、context)一起调用。
* 这些值可能与this.*不同,因为你的函数可能在receiveProps之后且在shouldComponentUpdate之前调用,
* 而且这个新的状态、道具和上下文还没有分配给它。
*/
Component.prototype.setState = function(partialState, callback) {
// ....
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

enqueue(入列)
将需要更新的state放入updater的队列中,然后整合在一起,一起执行。这也就导致了在一个事件中多次执行setState,值是不变的

add = () => {
    this.setState({count: this.state.count + 1})
    console.log(this.state.count)
    this.setState({count: this.state.count + 1})
    console.log(this.state.count)
    this.setState({count: this.state.count + 1})
    console.log(this.state.count)
    this.setState({count: this.state.count + 1}, () => {
        console.log(this.state.count)
    })
}
subtract = () => {
    this.setState({count: this.state.count - 1})
}

render() {
    return (
        <div>
            <p>{this.state.count}</p>
            <button onClick={this.add}>+</button>
            <button onClick={this.subtract}>-</button>

            <button id="add">原生+</button>
        </div>
    )
}

在add方法中,多次执行了this.setState,然而实际上只更新了一次会打印出下面的值在这里插入图片描述
而最后那个1,是setState的回调函数中打印出来的

来个不一样的写法

add = () => {
    this.setState({count: this.state.count + 1})
    console.log(this.state.count)
    setTimeout(() => {
        this.setState({count: this.state.count + 1})
        console.log(this.state.count)
        this.setState({count: this.state.count + 1})
        console.log(this.state.count)
        this.setState({count: this.state.count + 1})
        console.log(this.state.count)
    }, 0)
}

在这里插入图片描述
打印出来了这个结果,第一次打印的时候,state还没有更新,而在setTimeout中打印的都是更新后的数据。原理是啥呢?没找到在哪。。(后续找到了再更新吧)
更新第一版
setState是用一个updateQueue来实现的,并通过isUpdatePadding来确认是否在更新中,如果不是在更新中就说明已经结束了,对比新老值,然后进行渲染,在queue中进行的所有setState操作都会被合并执行,也就造成了有延迟(不会立即刷新)。
而setTimeout,会进入宏任务队列中,宏任务队列中的行为不走react那套更新机制,也就是不会进入updateQueue,所以他每执行一次都会重新渲染一次(TODO是否每次都会重新渲染,还需验证),也就导致了这个值是同步进行的。

还有另一种方式,写在原生事件中

componentDidMount() {
    document.getElementById("add").addEventListener("click", () => {
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
        this.setState({count: this.state.count + 1})
        console.log("原生++", this.state.count)
    })
}

render() {
	return (
		<div>
			<p>{this.state.count}</p>
			<button id="add">原生+</button>
		</div>
	)
}

这样子也可以跟setTimeout一样,在回调函数中,可以同步打印出来数据,但是更新还是会一下子更新的,比如我这里写了6次this.setState,他就会一次性+6,不会去渲染6次,这里应该还是用队列进行合并执行了。原理同样没找到。

据我不成熟的猜想,会不会是因为EventLoop的原因,这些都是宏任务,所以会另外开辟一个队列去执行宏任务中的任务队列。这个猜想需要去验证。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值