这个问题的答案是有道理的:If the props for a child component are unchanged, does React still re-render it?我也做了CodePen来验证它。
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.test === this.props.test);
console.log('shouldComponentUpdate');
return true;
}
但React的网站上有一条声明:
在收到新的道具或州时,在渲染之前调用
shouldComponentUpdate()
。
但实际上,即使子组件的props和state保持不变,仍然会调用shouldComponentUpdate()
。在官方陈述中是否存在错误,或者我误解了它?
答案 0 :(得分:0)
由于每秒都会重新呈现父组件Clock
,因此Child
组件也会被重新呈现。这是因为Clock
会在状态更新发生时完全重新呈现,因为时钟向前移动一秒钟。因此,由于Child
是Clock
的一部分,因此它也会被重新渲染。
React文档中的引用是正确的:
shouldComponentUpdate()
在呈现新的道具或状态时被调用。
每当重新呈现Child
时,每隔一秒钟就会一次又一次地收到道具test
,Clock
会被重新渲染。这是什么'新道具或国家'在这里指的是,它不一定是得到不同的,独特的道具。因此,每次重新shouldComponentUpdate
时都会调用Child
,因为在每次重新渲染时,test
都会获得道具Child
。