对react setState 的理解

setState是异步的对于这个我们随便测试一些就知道的,关于为什么是异步的可以参考博客的一些见解。

我们翻开react源码(version:16.3.2), 首先是 setState部分,看到这里接受两个参数partialState (局部状态,限定只有对象和函数可以作为第一个参数), callback

 

Component.prototype.setState = function (partialState, callback) {
  !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0;
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

 

然后是更新部分enqueueSetState 函数

enqueueSetState: function (instance, partialState, callback) {
      var fiber = get(instance);
      callback = callback === undefined ? null : callback;
      {
        warnOnInvalidCallback$1(callback, 'setState');
      }
      var expirationTime = computeExpirationForFiber(fiber);
      var update = {
        expirationTime: expirationTime,
        partialState: partialState,
        callback: callback,
        isReplace: false,
        isForced: false,
        capturedValue: null,
        next: null
      };
      insertUpdateIntoFiber(fiber, update);
      scheduleWork(fiber, expirationTime);
}
function insertUpdateIntoFiber(fiber, update) {
  ensureUpdateQueues(fiber);
  var queue1 = q1;
  var queue2 = q2;

  // Warn if an update is scheduled from inside an updater function.
  {
    if ((queue1.isProcessing || queue2 !== null && queue2.isProcessing) && !didWarnUpdateInsideUpdate) {
      warning(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 
'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); didWarnUpdateInsideUpdate = true; } } // If there's only one queue, add the update to that queue and exit. if (queue2 === null) { insertUpdateIntoQueue(queue1, update); return; } // If either queue is empty, we need to add to both queues. if (queue1.last === null || queue2.last === null) { insertUpdateIntoQueue(queue1, update); insertUpdateIntoQueue(queue2, update); return; } // If both lists are not empty, the last update is the same for both lists // because of structural sharing. So, we should only append to one of // the lists. insertUpdateIntoQueue(queue1, update); // But we still need to update the `last` pointer of queue2. queue2.last = update; } 

待续。。。

组件如下

import React, { Component } from 'react';

import './App.css';

class App extends Component {
state = {
count: 0
}
countChange = () => {
this.setState({
count: this.state.count + 1
})
this.setState({
count: this.state.count + 1
})
console.log('count change')
}
countChange2 = () => {
this.setState(preState => ({
count: preState.count + 1
}))
this.setState(preState => ({
count: preState.count + 1
}))
console.log('count change2')
}
UNSAFE_componentWillMount() {
console.log('~~')
}
render() {
return (
<div className="App">
<p>{this.state.count}</p>
<button onClick={this.countChange}>加一</button>
<button onClick={this.countChange2}>加一</button>
</div>
);
}
}
class App2 extends Component {
render() {
return <div><App></App></div>
}
}

export default App2;

测试中在setState中分别使用 对象参数和函数作为参数,结果说明 函数作为参数的方式是准确的,猜想,主要是对象的值已经确定了,而用使用函数是使用的preState作为参数,这个参数是在回调执行的时候传递下来的,所以是准确(在一个函数調用里面多次this.setState的情况下)。在第一种情况下面setState第二个参数是回调函数~在回调函数中使用this.state.count中获取也是对的。

 

 

 

转载于:https://www.cnblogs.com/www-wwr/p/9004709.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ReactsetState批处理是一种通过将多个setState调用包装在一个事务中来优化性能的技术。通过批量处理多个setState调用,可以减少不必要的重渲染和更新操作,从而提高应用的性能。 具体来说,当我们在React组件中调用setState时,React会将这些setState调用放入一个队列中。然后,React会根据一定的策略决定何时执行这些setState调用,以最小化组件的更新次数。 在React中,setState是异步的,这意味着在调用setState后,我们不能立即获取到更新后的state值。而批处理技术可以确保在一个事务中,一次性执行所有的setState调用,从而保证我们在同一个事务中获取到正确的state值。 在早期版本的React中,可以使用unstable_batchedUpdates方法来手动启用批处理。但是需要注意的是,这个API是不稳定的,在未来的版本中可能会发生变化。 使用批处理可以显著提升React应用的性能,特别是在需要执行多个连续的setState调用时。可以通过将多个setState调用包装在一个函数中,或者使用React提供的钩子函数(如componentDidMount)来实现批处理。 以上是关于ReactsetState批处理的一些介绍和示例。通过批处理技术,我们可以优化React组件的更新和渲染,提升应用的性能和用户体验。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [React setState 的异步与同步](https://blog.csdn.net/mChales_Liu/article/details/115952489)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [【React】深入理解setState](https://blog.csdn.net/qq_42996469/article/details/124395874)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值