React - 生命周期(二)

上一个写的是单个组件的生命周期,现在写一个,父子组件和兄弟组件之间生命周期的顺序
一、组件生命周期的执行次数是什么样子

  1. 只执行一次: constructor、componentWillMount、componentDidMount

  2. 执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate

  3. 有条件的执行:componentWillUnmount(页面离开,组件销毁时)

  4. 不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)

二、组件的生命周期执行顺序
假设组件嵌套关系是 App里有parent组件,parent组件有child组件
React - 生命周期(二)
如果不涉及到setState更新,第一次渲染的顺序如下:
React - 生命周期(二)

App: constructor --> componentWillMount --> render -->
parent: constructor --> componentWillMount --> render -->
child: constructor --> componentWillMount --> render -->
componentDidMount (child) --> componentDidMount (parent) --> componentDidMount (App)

这时候触发App的setState事件
React - 生命周期(二)

App: componentWillUpdate --> render -->
parent: componentWillReceiveProps --> componentWillUpdate --> render -->
child: componentWillReceiveProps --> componentWillUpdate --> render -->
componentDidUpdate (child) --> componentDidUpdate (parent) --> componentDidUpdate (App)

触发parent的setState
React - 生命周期(二)

parent: componentWillUpdate --> render -->
child: componentWillReceiveProps --> componentWillUpdate --> render -->
componentDidUpdate (child) --> componentDidUpdate (parent)

触发了child组件自身的setState
React - 生命周期(二)

child: componentWillUpdate --> render --> componentDidUpdate (child)

结论:

  1. 如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)

  2. 每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期

  3. 第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数
    React - 生命周期(二)
    React - 生命周期(二)
    React生命周期官方解析

    1. componentWillMount : 在渲染前调用,在客户端也在服务端。

    2. componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。

    3. componentWillReceiveProps : 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。

    4. shouldComponentUpdate : 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
      可以在你确认不需要更新组件时使用。

    5. componentWillUpdate : 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。

    6. componentDidUpdate : 在组件完成更新后立即调用。在初始化时不会被调用。

    7. componentWillUnmount: 在组件从 DOM 中移除的时候立刻被调用。

参考链接:

React生命周期执行顺序详解