javascript - 当 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
都是PureComponent
s。但是,他们每 1.5 秒都被调用一次,我不明白为什么。
forceUpdate()
我从文档中了解到的是shouldComponentUpdate
,false
即使Test
在Container
.
但是在控制台中是看到render Login
,render Container
和. 但是's还是没有改变。那么为什么会发生重新渲染呢?render Row
render Col
Container
props
state
从文档:
调用 forceUpdate() 将导致在组件上调用 render(),跳过 shouldComponentUpdate()。这将触发子组件的正常生命周期方法,包括每个子组件的 shouldComponentUpdate() 方法。如果标记发生变化,React 仍然只会更新 DOM。
所以即使这个组件在现实生活中没有任何意义,它至少也不应该重新Row
渲染Col
。
解决方案
也许我为时已晚,但我会将这个答案留给其他用户。原因是您正在使用forceUpdate
which ignores shouldComponentUpdate
。
存在的原因forceUpdate
是让组件一次又一次地重新渲染,忽略道具或状态更新,因为有时需要它。
文档参考: https ://reactjs.org/docs/react-component.html#forceupdate
推荐阅读
- php - 如何在 Prestashop 1.7 中获得具有属性值但没有属性组的“产品名称”?
- c# - 在 C# 中创建包含文件路径的命令行
- go - 尝试编写自定义规则
- javascript - 内插值应用于所有 ngfor 元素的跨度文本内容
- google-chrome-extension - 发布扩展程序时如何修复“广泛的主机权限”?
- laravel - 如何在控制器内保存pdf并传递pdf补丁
- python - 为什么 PyCharm 返回退出代码 246?
- python-3.x - 从字母表中的所有字母中选择不同的名称
- javascript - 如果元素有类
- botframework - LUIS 应用无法训练 - 应用训练失败:l_general:重新训练