對react setState 的理解

setState是異步的對於這個咱們隨便測試一些就知道的,關於爲何是異步的能夠參考博客的一些看法。javascript

咱們翻開react源碼(version:16.3.2), 首先是 setState部分,看到這裏接受兩個參數partialState (局部狀態,限定只有對象和函數能夠做爲第一個參數), callbackcss

 

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 函數java

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; } 

待續。。。react

組件以下segmentfault

import React, { Component } from 'react';app

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中獲取也是對的。異步

相關文章
相關標籤/搜索