我正在玩 ReactJS
' PureComponent
. 我有一个简单的组件,它只显示嵌套 PureComponent
中的一些文本:
export class Test extends React.Component<ITestProps> {
componentDidMount(): void {
window.setInterval(() => this.forceUpdate(), 1500);
}
private readonly extraSmall = { size: 10 };
render(): JSX.Element {
console.log("render Login");
return (
<Bootstrap.Container fluid={true}>
<Bootstrap.Row>
<Bootstrap.Col xs={this.extraSmall}>
RENDERED!
</Bootstrap.Col>
</Bootstrap.Row>
</Bootstrap.Container>
);
}
}
我已经意识到 render
只会在每个组件上调用一次 . Container
, Row
和 Col
都是 PureComponent
. 然而,他们都被称为每1.5秒一次,我不明白为什么 .
我从文档中了解到,即使父母在 forceUpdate()
期间更新,每个孩子也会调用 shouldComponentUpdate
,这应该为 Test
或至少 Container
的每个孩子返回 false
.
但在控制台中可以看到 render Login
, render Container
, render Row
和 render Col
. 但 Container
的 props
或 state
没有改变 . 那么为什么会有重新渲染呢?
来自文档:
调用forceUpdate()将导致在组件上调用render(),跳过shouldComponentUpdate() . 这将触发子组件的正常生命周期方法,包括每个子组件的shouldComponentUpdate()方法 . 如果标记更改,React仍将仅更新DOM .
所以,即使这个组件没有任何现实意义,它也不应该重新渲染至少 Row
和 Col
.