React 组件层次结构中 componentDidMount 的顺序 [英] Order of componentDidMount in React components hierarchy

查看:32
本文介绍了React 组件层次结构中 componentDidMount 的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的 React 应用程序:

组件ABC

组成

当组件B调用它的componentDidMount方法时,是不是所有组件都安装完成了?

或者换句话说,React 是否会在树中的所有组件都挂载后触发 componentDidMount?

或例如组件 B componentDidMount 在组件 A 挂载时被调用?

解决方案

根据文档,生命周期方法第一次挂载的顺序如下:

  1. 构造函数()
  2. componentWillMount()
  3. 渲染()
  4. componentDidMount()

假设您有这个组件:

A 类扩展组件 {使成为() {返回 (<div><B/><C/>

)}}

A被挂载时,它会触发componentDidMount().这将在渲染后发生.由于在 A 的 render() 被调用之前 B 和 C 不存在,所以 A 的挂载完成需要 B 和 C 完成各自的生命周期.A 的 componentDidMount() 将在 B 和 C 挂载后触发.A 的 componentWillMount() 在 A 的 render() 之前触发,因此它也在 B 或 C 安装之前触发

更新

从 React 16.3 开始,componentWillMountcomponentWillUpdatecomponentWillReceiveProps 一起开始弃用过程.上面的示例在任何 16.x 版本的 react 中都可以正常工作,但会收到弃用警告.有一些新方法取代了已弃用的方法,它们具有自己的生命周期.在 组件 API 文档 中有更多关于它们的信息.这是新生命周期的备忘单图

I have an React application that has the following structure:

component A is composed of B and C

When the component B calls it's componentDidMount method, is this true that all component finished mounting?

Or in other words does React fire componentDidMount after all components in the tree were mounted?

or e.g. Components B componentDidMount is called when component A mounted?

解决方案

According to the documentation, the order of the lifecycle methods on first mount is as follows:

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount()

Let's say you have this component:

class A extends Component {
  render() {
    return (
      <div>
        <B />
        <C />
      </div>
    )
  }
}

When A is mounted, it will fire componentDidMount(). That will happen after render. Since B and C do not exist before A's render() is called, the completion of A's mounting requires that B and C finish their respective lifecycles. A's componentDidMount() will fire after B and C are mounted. A's componentWillMount() fires before A's render(), and therefore it also fires before B or C are mounted

UPDATE

As of React 16.3, componentWillMount starts the deprecation process, along with componentWillUpdate and componentWillReceiveProps. The above example will work fine in any 16.x release of react, but it will get deprecation warnings. There are new methods that take place of the deprecated ones, with their own lifecycle. More about them in the component API docs. Here is a cheatsheet diagram for the new lifecycles

这篇关于React 组件层次结构中 componentDidMount 的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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