? 一直對React組件的生命周期理解的不夠深刻,例如在React官網(wǎng)中,有這樣一句話來描述shouldComponentUpdate()方法:
shouldComponentUpdate()is invoked before rendering when new props or state are being received.
? 我對這句話的理解是:shouldComponentUpdate()只有在props或state更新的時候才會被調(diào)用。于是很自然的,我一直默認這樣一種場景:當父組件進行重新渲染(re-render)操作的時候,如果子組件的props或state沒有改變,那么子組件就不會調(diào)用shouldComponentUpdate(),進而也不會調(diào)用render()方法。但是,事實是這樣的嗎?
? 我們建立這樣一個場景:父組件能夠周期性的進行渲染,子組件接收父組件傳遞的一個props,但并不曾改變它,即驗證該場景下shouldComponentUpdate()是否會被調(diào)用。父組件的render()方法如下:
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<Child test={1}/>
</div>
);
}
? 俗話說的好,talk is cheap, show me the code。使用CodePen來創(chuàng)建這樣的一個場景。在子組件所有的生命周期函數(shù)中打上log,特別的在shouldComponentUpdate()中驗證nextProps和this.props:
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.test === this.props.test);
console.log('shouldComponentUpdate');
return true;
}
? 結(jié)果大大出乎我的意料,console.log(nextProps.test === this.props.test);輸出永遠是true,但是控制臺內(nèi)不停地打印出:
"componentWillReceiveProps"
true
"shouldComponentUpdate"
"componentWillUpdate"
"render"
"componentDidUpdate"
? 子組件內(nèi)并沒有任何props或state的改變,但是子組件依然不停的進行re-render!這跟文章開頭給出的React官網(wǎng)的引用好像背道而馳!對于該問題,本人還不能作出很好的回答,于是在stackoverflow上放出了問題,等待高人解答吧。但目前可以明確的一點是:當父組件進行重新渲染操作時,即使子組件的props或state沒有做出任何改變,也會同樣進行重新渲染。