props和状态未更改时,React PureComponent更新

时间:2018-06-26 00:03:34

标签: javascript reactjs typescript

我目前正在玩ReactJS'PureComponent。我有一个简单的组件,它只在嵌套的PureComponent s中显示一些文本:

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在每个组件上只会被调用一次。 ContainerRowCol均为PureComponent。 但是,他们每1.5秒就会接到一次电话,我不明白为什么。

我从文档中了解到,即使父项在forceUpdate()期间进行了更新,每个孩子也会调用shouldComponentUpdate,而false会为{{ 1}}或至少Test

但是在控制台中看到Containerrender Loginrender Containerrender Row。但是render Col的{​​{1}}或Container并没有改变。那么为什么要进行重新渲染?

从文档中

  

调用forceUpdate()将导致在组件上调用render(),而应跳过shouldComponentUpdate()。   这将触发子组件的正常生命周期方法,包括shouldComponentUpdate()   每个孩子的方法。如果标记发生更改,React仍然只会更新DOM。

因此,即使该组件没有任何现实意义,也不应至少重新渲染propsstate

1 个答案:

答案 0 :(得分:1)

也许我来晚了,但是我将把这个答案留给其他用户。 原因是您使用的forceUpdate忽略了shouldComponentUpdate

forceUpdate存在的原因是使组件一次又一次地重新渲染,而忽略了props或状态更新,因为有时是必需的。

文档参考: https://reactjs.org/docs/react-component.html#forceupdate

相关问题