前言
這篇文章主要是為了紀(jì)錄一些自己對(duì)于setState的認(rèn)識(shí)的不斷深入的過程寇蚊。我覺得這過程對(duì)我自己來說很有價(jià)值,不光是層層遞進(jìn)的了解一個(gè)API的執(zhí)行機(jī)制开缎,更對(duì)react總體的設(shè)計(jì)有了更為深入的認(rèn)識(shí)棕叫。
第一階段 初識(shí)setState
使用過React的應(yīng)該都知道,在React中奕删,一個(gè)組件中要讀取當(dāng)前狀態(tài)需要訪問this.state俺泣,但是更新狀態(tài)卻需要使用this.setState,不是直接在this.state上修改,就比如這樣:
//讀取狀態(tài)
const count = this.state.count伏钠;
//更新狀態(tài)
this.setState({count: count + 1})横漏;
//無(wú)意義的修改
this.state.count = count + 1;
其實(shí)這主要有幾點(diǎn)考慮,首先this.state說到底只是一個(gè)對(duì)象熟掂,單純的去修改一個(gè)對(duì)象的值是毫無(wú)意義的缎浇,在React中只有去驅(qū)動(dòng)UI的更新才會(huì)有意義,因此雖然我們可以嘗試直接改變this.state打掘,但并沒有驅(qū)動(dòng)UI的重新渲染华畏,因此這種操作也就毫無(wú)意義。也正是由于這個(gè)原因尊蚁,我們就需要使用this.setState來驅(qū)動(dòng)組件的更新過程。
然后在我剛學(xué)習(xí)React時(shí)侣夷,我就看見了這段很經(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í)沒怎么看懂的React文檔中的一些話:狀態(tài)更新可能是異步的决帖,狀態(tài)更新合并。恩蓖捶,沒毛病地回,因?yàn)楫惒角視?huì)合并,因此這三條語(yǔ)句合并為一條語(yǔ)句了俊鱼,所以就只執(zhí)行一次刻像。然后就扭頭溜了,并沒有去思考一些深層次的問題并闲。
第二階段 setState理解的進(jìn)階
但是隨著對(duì)React的理解的逐步加深恬惯,我開始對(duì)setState有了更加深的理解:
首先我意識(shí)到this.setState會(huì)通過引發(fā)一次組件的更新過程來引發(fā)重新繪制垫毙。也就是說setState的調(diào)用會(huì)引起React的更新生命周期的四個(gè)函數(shù)的依次調(diào)用:
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
我們都知道,在React生命周期函數(shù)里,以render函數(shù)為界晴圾,無(wú)論是掛載過程和更新過程,在render之前的幾個(gè)生命周期函數(shù)辛慰,this.state和Props都是不會(huì)發(fā)生更新的超升,直到render函數(shù)執(zhí)行完畢后,this.state才會(huì)得到更新宏浩。(有一個(gè)例外:當(dāng)shouldComponentUpdate函數(shù)返回false知残,這時(shí)候更新過程就被中斷了,render函數(shù)也不會(huì)被調(diào)用了,這時(shí)候React不會(huì)放棄掉對(duì)this.state的更新的求妹,所以雖然不調(diào)用render乏盐,依然會(huì)更新this.state。)
React的官方文檔有提到過這么一句話:
狀態(tài)更新會(huì)合并(也就是說多次setstate函數(shù)調(diào)用產(chǎn)生的效果會(huì)合并)制恍。
起初我對(duì)這句話理解并不是很深刻,但按照官方文檔的代碼示例寫了這么一段代碼:
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ì)被合并起來,排成一排净神,到最后一次解決何吝。但對(duì)其設(shè)計(jì)的原因并不理解,只知道這樣有利于性能(也是在文檔上看到的)鹃唯。
直到理解上面React生命周期函數(shù)的原理后爱榕,我才理解了setState關(guān)于這個(gè)設(shè)計(jì)的意圖。
前面我們提到過坡慌,每一次使用setState都會(huì)調(diào)用一次更新的生命周期黔酥,如果每一次this.serState()都調(diào)用一次上面那四個(gè)生命周期函數(shù),雖然以上四個(gè)函數(shù)都是純函數(shù)洪橘,性能浪費(fèi)上還好跪者,但render函數(shù)會(huì)將結(jié)果拿去做Virtual DOM比較和更新DOM樹,這個(gè)就比較費(fèi)時(shí)間熄求。因此渣玲,將多個(gè)this.setSate進(jìn)行合并,render函數(shù)就能夠?qū)⒑喜⒑蟮膖his.setState()的結(jié)果一次性的與Virtual DOM比較然后更新DOM樹弟晚,這樣就能夠用有效的提升性能忘衍。
除此之外,我還認(rèn)為setState的設(shè)計(jì)十分巧妙指巡,一般來說只在render函數(shù)后才會(huì)進(jìn)行更新this.state淑履。這其實(shí)也避免了React16的Fiber可能會(huì)產(chǎn)生的一個(gè)問題:由于Fiber下的組件更新是可以中斷,也就是說在一個(gè)組件的更新過程中藻雪,可能更新到一半的時(shí)候就由于其他原因而中斷更新秘噪,回去做更重要的事情了,在做完更重要的事情后勉耀,再回來更新這個(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()到底是怎樣一種騷操作畴栖?...等等随静。然后我又看見了這段經(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)吗讶,這波操作我看不懂燎猛!
于是硬著頭皮打開了React源碼,開始一波瞎分析:
首先就是setState了照皆,可以看出它接受兩個(gè)參數(shù)partialState和callback重绷,其中partialState顧名思義就是部分state,起這個(gè)名字也能就是想表達(dá)它的state沒有改變(瞎猜的膜毁。论寨。。)爽茴。以下是省略了一部分的代碼,只看核心部分绰垂。
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);
}
// 通過enqueueUpdate執(zhí)行state更新
function enqueueUpdate(component) {
ensureInjected();
// batchingStrategy是批量更新策略室奏,isBatchingUpdates表示是否處于批量更新過程
// 最開始默認(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表示是否處于批量更新過程
// 最開始默認(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)用
// 但一般來說念恍,處于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ì)通過enqueueUpdate執(zhí)行state更新,就像上面那樣有兩種更新的模式瞳氓,一種是批量更新模式策彤,將組建保存在dirtyComponents;另一種非批量模式,將會(huì)遍歷dirtyComponents,對(duì)每一個(gè)dirtyComponents調(diào)用updateComponent方法店诗。就像這張圖:
至于批量與非批量模式裹刮,會(huì)通過ReactDefaultBatchingStrategy中的isBatchingUpdates屬性來進(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é)起來就是這樣:
- this.setState首先會(huì)把state推入pendingState隊(duì)列中
- 然后將組件標(biāo)記為dirty
- React中有事務(wù)的概念霜第,最常見的就是更新事務(wù)葛家,如果不在事務(wù)中,則會(huì)開啟一次新的更新事務(wù)泌类,更新事務(wù)執(zhí)行的操作就是把組件標(biāo)記為dirty癞谒。
- 判斷是否處于batch update
- 是的話,保存組建于dirtyComponent中刃榨,在事務(wù)結(jié)束的時(shí)候才會(huì)通過 ReactUpdates.flushBatchedUpdates 方法將所有的臨時(shí) state merge 并計(jì)算出最新的 props 及 state弹砚,然后將其批量執(zhí)行,最后再關(guān)閉結(jié)束事務(wù)枢希。
- 不是的話桌吃,直接開啟一次新的更新事務(wù),在標(biāo)記為dirty之后苞轿,直接開始更新組件茅诱。因此當(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)用。