这个问题的答案是有道理的: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()
is invoked before rendering when new props or state are being received.
但实际上,即使子组件的 props 和状态保持不变,shouldComponentUpdate()
仍然会被调用。官方说法有误吗,还是我理解错了?
最佳答案
由于父组件 Clock
每秒都会重新渲染,因此 Child
组件也会重新渲染。这是因为每当发生状态更新时,随着时钟前进一秒,Clock
就会完全重新渲染。因此,由于 Child
是 Clock
的一部分,它也会被重新渲染。
React 文档中的引用是正确的:
shouldComponentUpdate()
is invoked before rendering when new props or state are being received.
每当 Child
重新渲染时,Clock
每秒重新渲染后都会一次又一次地接收到 test
属性。这就是“新 Prop 或状态”在这里所指的,不一定是它获得不同的、独特的 Prop 。因此,每次重新渲染 Child
时,都会调用 shouldComponentUpdate
,因为每次都会将 prop test
赋予给 Child
重新渲染。
关于reactjs - 如果子组件的 props 保持不变,为什么 React 会重新渲染它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829272/