一直对React组件的生命周期理解的不够深刻,例如在React官网中,有这样一句话来描述shouldComponentUpdate()方法:
shouldComponentUpdate() is invoked before rendering when new props or state are being received.
我对这句话的理解是:shouldComponentUpdate()只有在props或state更新的时候才会被调用。于是很自然的,我一直默认这样一种场景:当父组件进行重新渲染(re-render)操作的时候,如果子组件的props或state没有改变,那么子组件就不会调用shouldComponentUpdate(),进而也不会调用render()方法。但是,事实是这样的吗?
我们建立这样一个场景:父组件能够周期性的进行渲染,子组件接收父组件传递的一个props,但并不曾改变它,即验证该场景下shouldComponentUpdate()是否会被调用。父组件的render()方法如下:
render() {
return (
Hello, world!
It is {this.state.date.toLocaleTimeString()}.
);
}
俗话说的好,talk is cheap, show me the code。使用CodePen来创建这样的一个场景。在子组件所有的生命周期函数中打上log,特别的在shouldComponentUpdate()中验证nextProps和this.props:
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.test === this.props.test);
console.log('shouldComponentUpdate');
return true;
}
结果大大出乎我的意料,console.log(nextProps.test === this.props.test);输出永远是true,但是控制台内不停地打印出:
"componentWillReceiveProps"
true
"shouldComponentUpdate"
"componentWillUpdate"
"render"
"componentDidUpdate"
子组件内并没有任何props或state的改变,但是子组件依然不停的进行re-render!这跟文章开头给出的React官网的引用好像背道而驰!对于该问题,本人还不能作出很好的回答,于是在stackoverflow上放出了问题,等待高人解答吧。但目前可以明确的一点是:当父组件进行重新渲染操作时,即使子组件的props或state没有做出任何改变,也会同样进行重新渲染。