什么时候触发`componentDidMount`? [英] When exactly is `componentDidMount` fired?

查看:181
本文介绍了什么时候触发`componentDidMount`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 React 中经常遇到的问题.componentDidMount 方法保证在第一次渲染组件时被触发,所以它看起来是一个自然的地方来进行 DOM 测量,比如高度和偏移量.但是,在组件生命周期的这一点上,我多次收到错误的样式读数.当我与调试器中断时,组件 在 DOM 中,但它尚未绘制在屏幕上.大多数情况下,宽度/高度设置为 100% 的元素都会出现这个问题.当我在 componentDidUpdate 中进行测量时 - 一切正常,但此方法不会在组件的初始渲染时触发.

This is a recurring problem I have with React. The componentDidMount method is guaranteed to be fired when the component is rendered for the first time so it seems like a natural place to take DOM measurements like heights and offsets. However, many times I receive wrong style readings at this point of the component's lifecycle. The component is in the DOM, when I break with the debugger, but it's not yet painted on the screen. I get this problem with elements that have width/height set to 100% mostly. When I take measurements in componentDidUpdate - everything works fine, but this method will not fire at the initial render of the component.

所以我的问题是 - componentDidMount 什么时候被触发,因为在所有浏览器绘制完成后它显然没有被触发.

So my question is - when exactly is componentDidMount fired because it's obviously not fired after all the browser paints are done.

这个 Stackoverflow 问题涉及同一主题:

它还引用了 这个 github 对话,解释了所发生的事情

It also references this github conversation that explains what happens

推荐答案

在 React 组件树中,componentDidMount() 在所有子组件也都已安装后被触发.这意味着,任何组件的 componentDidMount() 在其父组件被挂载之前被触发.

Inside a react component tree, componentDidMount() is fired after all children components have also been mounted. This means, that any component's componentDidMount() is fired before its parent has been mounted.

因此,如果您想测量 DOM 位置和大小等,使用子组件的 componentDidMount() 是不安全的地方/时间来执行此操作.

So if you want to measure DOM position and sizes etc, using componentDidMount() of a child component is an unsafe place/ time to do this.

在您的情况下:要从 100% 宽度/高度组件中获得准确读数,进行此类测量的安全位置应在 top<的 componentDidMount() 内/em> 反应组件.
100% 是相对于父/容器的宽度/高度.因此,只有在安装父级后才能进行测量.

In your case: to get accurate reading from 100% width/height components, a safe place to take such measurements would be inside the componentDidMount() of the top react component.
100% is a width/height relative to the parent/ container. So measurements can only be taken after the parent has been mounted too.

这篇关于什么时候触发`componentDidMount`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆