如果React的道具保持不变,为什么React会重新渲染?

时间:2017-06-29 15:26:00

标签: reactjs

这个问题的答案是有道理的: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()。在官方陈述中是否存在错误,或者我误解了它?

1 个答案:

答案 0 :(得分:0)

由于每秒都会重新呈现父组件Clock,因此Child组件也会被重新呈现。这是因为Clock会在状态更新发生时完全重新呈现,因为时钟向前移动一秒钟。因此,由于ChildClock的一部分,因此它也会被重新渲染。

React文档中的引用是正确的:

  

shouldComponentUpdate()在呈现新的道具或状态时被调用。

每当重新呈现Child时,每隔一秒钟就会一次又一次地收到道具testClock会被重新渲染。这是什么'新道具或国家'在这里指的是,它不一定是得到不同的,独特的道具。因此,每次重新shouldComponentUpdate时都会调用Child,因为在每次重新渲染时,test都会获得道具Child