首页 > 解决方案 > 当 props 和 state 没有改变时 React PureComponent 更新

问题描述

我目前正在玩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在每个组件上只会调用一次。Container,Row并且Col都是PureComponents。但是,他们每 1.5 秒都被调用一次,我不明白为什么。

forceUpdate()我从文档中了解到的是shouldComponentUpdatefalse即使TestContainer.

但是在控制台中是看到render Login,render Container和. 但是's还是没有改变。那么为什么会发生重新渲染呢?render Rowrender ColContainerpropsstate

从文档:

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

所以即使这个组件在现实生活中没有任何意义,它至少也不应该重新Row渲染Col

标签: javascriptreactjstypescript

解决方案


也许我为时已晚,但我会将这个答案留给其他用户。原因是您正在使用forceUpdatewhich ignores shouldComponentUpdate

存在的原因forceUpdate是让组件一次又一次地重新渲染,忽略道具或状态更新,因为有时需要它。

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


推荐阅读