在浏览钩子文档时,我无意中发现了useLayoutEffect的时间与componentDidMount和componentDidUpdate是如何相同的。我很难理解这个阶段的行为。因为这个阶段和油漆阶段是同步的,所以我开始检验一个假设。
如果我在render和componentDidUpdate中更新元素的高度,那么当我读取元素的高度时,不应该用最新的值来更新它。正如我所理解的,只有在对DOM进行反应后,才会发生reflow/DOM。
因此,为了测试这个阶段的行为,我创建了以下元素
```<div id="random_test_dummy" style={{height: `${this.state.heightRandom}px`}}></div>```Initialized the heightRandom in the constructor as follows:
```javascriptthis.state={heightRandom: 5};
然后设置一个setInterval调用,如下所示:
```componentWillMount() {this.clearInterval = setInterval(() => { this.setState((prevState) => ({heightRandom: prevState.heightRandom+5}));}, 10000);}`
So basically every 5 seconds I update the height of _random\_test\_dummy_ element by 5px.
Now I setup the following code in componentDidUpdate
```javascript alert(document.getElementById("random_test_dummy").clientHeight);
}```现在,当我的代码运行时,警报显示为10,但是屏幕还没有更新,它的高度是chrome DevTools的elements选项卡中的5px。
我不明白如何更新从DOM读取的高度,而不更新屏幕上的节点。如果删除警报并在console.log()语句上添加调试点,则DOM节点将在屏幕上更新。这个同步更新阶段实际上是如何运行的?
发布于 2022-03-27 06:12:03
根据我的理解。进行更新dom测量的原因是因为componentDidUpdate在完成完全绘制之前运行,测量值在那里,但视觉反馈并不是因为浏览器尚未绘制更改。
https://stackoverflow.com/questions/59105766
复制相似问题