前言
這篇文章主要是為了紀(jì)錄一些自己對(duì)于setState的認(rèn)識(shí)的不斷深入的過(guò)程。我覺(jué)得這過(guò)程對(duì)我自己來(lái)說(shuō)很有價(jià)值,不光是層層遞進(jìn)的了解一個(gè)API的執(zhí)行機(jī)制,更對(duì)react總體的設(shè)計(jì)有了更為深入的認(rèn)識(shí)。
第一階段 初識(shí)setState
使用過(guò)React的應(yīng)該都知道,在React中,一個(gè)組件中要讀取當(dāng)前狀態(tài)需要訪問(wèn)this.state,但是更新?tīng)顟B(tài)卻需要使用this.setState,不是直接在this.state上修改,就比如這樣:
//讀取狀態(tài)
const count = this.state.count;
//更新?tīng)顟B(tài)
this.setState({count: count + 1});
//無(wú)意義的修改
this.state.count = count + 1;
其實(shí)這主要有幾點(diǎn)考慮,首先this.state說(shuō)到底只是一個(gè)對(duì)象,單純的去修改一個(gè)對(duì)象的值是毫無(wú)意義的,在React中只有去驅(qū)動(dòng)UI的更新才會(huì)有意義,因此雖然我們可以嘗試直接改變this.state,但并沒(méi)有驅(qū)動(dòng)UI的重新渲染,因此這種操作也就毫無(wú)意義。也正是由于這個(gè)原因,我們就需要使用this.setState來(lái)驅(qū)動(dòng)組件的更新過(guò)程。
然后在我剛學(xué)習(xí)React時(shí),我就看見(jiàn)了這段很經(jīng)典的代碼:
function incrementMultiple() {
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
}
作為一名JSer,我看完就毫不猶豫的想到,這特么不就是count的值加3么,但轉(zhuǎn)眼看了下面的答案,光速打臉,實(shí)際的結(jié)果是state只增加了1。然后我就不由想到當(dāng)時(shí)沒(méi)怎么看懂的React文檔中的一些話:狀態(tài)更新可能是異步的,狀態(tài)更新合并。恩,沒(méi)毛病,因?yàn)楫惒角視?huì)合并,因此這三條語(yǔ)句合并為一條語(yǔ)句了,所以就只執(zhí)行一次。然后就扭頭溜了,并沒(méi)有去思考一些深層次的問(wèn)題。
第二階段 setState理解的進(jìn)階
但是隨著對(duì)React的理解的逐步加深,我開(kāi)始對(duì)setState有了更加深的理解:
首先我意識(shí)到this.setState會(huì)通過(guò)引發(fā)一次組件的更新過(guò)程來(lái)引發(fā)重新繪制。也就是說(shuō)setState的調(diào)用會(huì)引起React的更新生命周期的四個(gè)函數(shù)的依次調(diào)用:
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
我們都知道,在React生命周期函數(shù)里,以render函數(shù)為界,無(wú)論是掛載過(guò)程和更新過(guò)程,在render之前的幾個(gè)生命周期函數(shù),this.state和Props都是不會(huì)發(fā)生更新的,直到render函數(shù)執(zhí)行完畢后,this.state才會(huì)得到更新。(有一個(gè)例外:當(dāng)shouldComponentUpdate函數(shù)返回false,這時(shí)候更新過(guò)程就被中斷了,render函數(shù)也不會(huì)被調(diào)用了,這時(shí)候React不會(huì)放棄掉對(duì)this.state的更新的,所以雖然不調(diào)用render,依然會(huì)更新this.state。)
React的官方文檔有提到過(guò)這么一句話:
狀態(tài)更新會(huì)合并(也就是說(shuō)多次setstate函數(shù)調(diào)用產(chǎn)生的效果會(huì)合并)。
起初我對(duì)這句話理解并不是很深刻,但按照官方文檔的代碼示例寫(xiě)了這么一段代碼:
function updateName() {
this.setState({Age: '22'})
this.setState({Name: 'srtian'})
}
果然執(zhí)行結(jié)果與以下代碼是等價(jià)的
function updateName() {
this.setState({Age: '22', Name: 'srtian})
}
于是我將其理解為一個(gè)隊(duì)列,每個(gè)this.setState()都會(huì)被合并起來(lái),排成一排,到最后一次解決。但對(duì)其設(shè)計(jì)的原因并不理解,只知道這樣有利于性能(也是在文檔上看到的)。
直到理解上面React生命周期函數(shù)的原理后,我才理解了setState關(guān)于這個(gè)設(shè)計(jì)的意圖。
前面我們提到過(guò),每一次使用setState都會(huì)調(diào)用一次更新的生命周期,如果每一次this.serState()都調(diào)用一次上面那四個(gè)生命周期函數(shù),雖然以上四個(gè)函數(shù)都是純函數(shù),性能浪費(fèi)上還好,但render函數(shù)會(huì)將結(jié)果拿去做Virtual DOM比較和更新DOM樹(shù),這個(gè)就比較費(fèi)時(shí)間。因此,將多個(gè)this.setSate進(jìn)行合并,render函數(shù)就能夠?qū)⒑喜⒑蟮膖his.setState()的結(jié)果一次性的與Virtual DOM比較然后更新DOM樹(shù),這樣就能夠用有效的提升性能。
除此之外,我還認(rèn)為setState的設(shè)計(jì)十分巧妙,一般來(lái)說(shuō)只在render函數(shù)后才會(huì)進(jìn)行更新this.state。這其實(shí)也避免了React16的Fiber可能會(huì)產(chǎn)生的一個(gè)問(wèn)題:由于Fiber下的組件更新是可以中斷,也就是說(shuō)在一個(gè)組件的更新過(guò)程中,可能更新到一半的時(shí)候就由于其他原因而中斷更新,回去做更重要的事情了,在做完更重要的事情后,再回來(lái)更新這個(gè)組件,這會(huì)導(dǎo)致前面的那些生命周期函數(shù)可能會(huì)執(zhí)行多次。因此如果在render之前this.setState()就改變狀態(tài)的話,很有可能就會(huì)導(dǎo)致組件狀態(tài)的多次更新,從而導(dǎo)致組件狀態(tài)的混亂。
第三階段 從源碼理解setstate
這是React15.6版本,由于React16變動(dòng)較大,setState的調(diào)用棧發(fā)生變動(dòng),因此僅供參考。
經(jīng)歷了上面那個(gè)階段,我算是對(duì)setState有那么一些理解了,但還是不能理解很多東西比如:this.setState()的是怎么合并的?setState()到底是怎樣一種騷操作?...等等。然后我又看見(jiàn)了這段經(jīng)典的代碼:
class Example extends React.Component {
constructor() {
super();
this.state = {
val: 0
};
}
componentDidMount() {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 1 次 log
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 2 次 log
setTimeout(() => {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 3 次 log
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 4 次 log
}, 0);
}
render() {
return null;
}
};
恩!按照我多年經(jīng)驗(yàn),這波操作我看不懂!
于是硬著頭皮打開(kāi)了React源碼,開(kāi)始一波瞎分析:
首先就是setState了,可以看出它接受兩個(gè)參數(shù)partialState和callback,其中partialState顧名思義就是部分state,起這個(gè)名字也能就是想表達(dá)它的state沒(méi)有改變(瞎猜的。。。)。以下是省略了一部分的代碼,只看核心部分。
ReactComponent.prototype.setState = function(partialState, callback) {
invariant(
typeof partialState === 'object' ||
typeof partialState === 'function' ||
partialState == null,
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.',
);
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
enqueueSetState: function(publicInstance, partialState) {
if (__DEV__) {
ReactInstrumentation.debugTool.onSetState();
warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().',
);
}
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'setState',
);
if (!internalInstance) {
return;
}
var queue =
internalInstance._pendingStateQueue ||
(internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
}
// 通過(guò)enqueueUpdate執(zhí)行state更新
function enqueueUpdate(component) {
ensureInjected();
// batchingStrategy是批量更新策略,isBatchingUpdates表示是否處于批量更新過(guò)程
// 最開(kāi)始默認(rèn)值為false
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1;
}
}
// 對(duì)_pendingElement, _pendingStateQueue, _pendingForceUpdate進(jìn)行判斷,
// _pendingStateQueue由于會(huì)對(duì)state進(jìn)行修改,所以不為空,
// 然后會(huì)調(diào)用updateComponent方法
performUpdateIfNecessary: function(transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(
this,
this._pendingElement,
transaction,
this._context,
);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(
transaction,
this._currentElement,
this._currentElement,
this._context,
this._context,
);
} else {
this._updateBatchNumber = null;
}
},
其中這段代碼需要額外注意:
// batchingStrategy是批量更新策略,isBatchingUpdates表示是否處于批量更新過(guò)程
// 最開(kāi)始默認(rèn)值為false
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1;
}
上面這段代碼的意思就是如果是處于批量更新模式,也就是isBatchingUpdates為true時(shí),不進(jìn)行state的更新操作,而是將需要更新的component添加到dirtyComponents數(shù)組中。
如果不處于批量更新模式,則對(duì)所有隊(duì)列中的更新執(zhí)行batchedUpdates方法。
然后可以找到了這個(gè)batchedUpdates:
var ReactDefaultBatchingStrategy = {
// 也就是上面提到的默認(rèn)為false
isBatchingUpdates: false,
// 這個(gè)方法只有在isBatchingUpdates: false時(shí)才會(huì)調(diào)用
// 但一般來(lái)說(shuō),處于react大事務(wù)中時(shí),會(huì)在render中的_renderNewRootComponent中將其設(shè)置為true。
batchedUpdates: function(callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
return callback(a, b, c, d, e);
} else {
return transaction.perform(callback, null, a, b, c, d, e);
}
},
看到這我總算理解了,當(dāng)我們調(diào)用setState時(shí),最終會(huì)通過(guò)enqueueUpdate執(zhí)行state更新,就像上面那樣有兩種更新的模式,一種是批量更新模式,將組建保存在dirtyComponents;另一種非批量模式,將會(huì)遍歷dirtyComponents,對(duì)每一個(gè)dirtyComponents調(diào)用updateComponent方法。就像這張圖:

至于批量與非批量模式,會(huì)通過(guò)ReactDefaultBatchingStrategy中的isBatchingUpdates屬性來(lái)進(jìn)行判斷。在非批量模式下,會(huì)立即應(yīng)用新的state;而在批量模式下,需要更新state的組件會(huì)被push 到dirtyComponents,再執(zhí)行更新。
所以我們?cè)倏辞懊娴哪芹绱a:
class Example extends React.Component {
constructor() {
super();
this.state = {
val: 0
};
}
componentDidMount() {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 1 次 log
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 2 次 log
setTimeout(() => {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 3 次 log
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 4 次 log
}, 0);
}
render() {
return null;
}
};
就不難看出它的答案是 0, 0, 2, 3。
總結(jié)起來(lái)就是這樣:
- this.setState首先會(huì)把state推入pendingState隊(duì)列中
- 然后將組件標(biāo)記為dirty
- React中有事務(wù)的概念,最常見(jiàn)的就是更新事務(wù),如果不在事務(wù)中,則會(huì)開(kāi)啟一次新的更新事務(wù),更新事務(wù)執(zhí)行的操作就是把組件標(biāo)記為dirty。
- 判斷是否處于batch update
- 是的話,保存組建于dirtyComponent中,在事務(wù)結(jié)束的時(shí)候才會(huì)通過(guò) ReactUpdates.flushBatchedUpdates 方法將所有的臨時(shí) state merge 并計(jì)算出最新的 props 及 state,然后將其批量執(zhí)行,最后再關(guān)閉結(jié)束事務(wù)。
- 不是的話,直接開(kāi)啟一次新的更新事務(wù),在標(biāo)記為dirty之后,直接開(kāi)始更新組件。因此當(dāng)setState執(zhí)行完畢后,組件就更新完畢了,所以會(huì)造成定時(shí)器同步更新的情況。
另外還有就是updateComponent方法,這也很重要:
{ // 會(huì)檢測(cè)組件中的state和props是否發(fā)生變化,有變化才會(huì)進(jìn)行更新;
// 如果shouldUpdateComponent函數(shù)中返回false則不會(huì)執(zhí)行組件的更新
updateComponent: function (transaction,
prevParentElement,
nextParentElement,
prevUnmaskedContext,
nextUnmaskedContext,) {
var inst = this._instance;
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (__DEV__) {
shouldUpdate = measureLifeCyclePerf(
() => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
this._debugID,
'shouldComponentUpdate',
);
} else {
shouldUpdate = inst.shouldComponentUpdate(
nextProps,
nextState,
nextContext,
);
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate =
!shallowEqual(prevProps, nextProps) ||
!shallowEqual(inst.state, nextState);
}
}
}
},
// 該方法會(huì)合并需要更新的state,然后加入到更新隊(duì)列中
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = Object.assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
Object.assign(
nextState,
typeof partial === 'function'
? partial.call(inst, nextState, props, context)
: partial,
);
}
return nextState;
}
};
發(fā)現(xiàn)它會(huì)調(diào)用shouldComponentUpdate和componentWillUpdate方法,看到這不由理解了一個(gè)定律:不要在shouldComponentUpdate和componentWillUpdate中調(diào)用setState。如果在這兩個(gè)生命周期里調(diào)用setState,會(huì)造成造成循環(huán)調(diào)用。