深入理解React生命周期

React主要思想是通过构建可复用组件来构建用户界面。所谓组件就是有限状态机。通过状态渲染对应的界面,且每个组件都有自己的生命周期,它规定了组件的状态和方法需要在哪个阶段改变和执行。

有限状态机,表示有限个状态以及在这些状态之间的转移和动作行为的模型。一般通过状态,事件,转换和动作来描述有限状态机。React正是利用这一概念,通过管理状态来实现对组件的管理。

初探React生命周期

在定义React组件时,我们会根据需要在组件生命周期的不同阶段实现不同的逻辑。

首次挂载,按顺序执行,getDefaultProps--->getInitialState---> componentWillMount--->render--->componentDidMount

组件卸载时,执行componentWillUnmount.

当组件重新挂载组件时,此时按顺序执行getInitialState--->componentWillMount--->render--->componentDidMount,但不执行getDefaultProps.

当再次渲染组件时,组件接受到更新状态,此时执行顺序是componentWillReceiveProps--->shouldComponentUpdate,--->componentWillUpdate--->render--->componentDidUpdate

想必大家看了上面的流程肯定有一些疑惑,接下来我们详细解答一下。

详解React生命周期

自定义组件的生命周期主要通过3个阶段进行管理MOUNTING, RECEIVE_PROPSUNMOUNTING,他们负责组件当前所处的阶段,应该执行生命周期中的哪个步骤。

这三个阶段分别对应3种方法,分别为:mountComponent, updateComponent, unmountComponent,每个方法都提供了几种处理方法,其中带will前缀的方法在进入状态之前调用带did前缀的方法在进入状态之后调用。

深入理解React生命周期

1. 阶段一:MOUNTING

mountComponent负责管理生命周期中的getInitialState,componentWillMount, render, componentDidMount。

由于getDeaultProps是通过构造函数进行管理的,所以也是整个生命周期中最为先开始执行的。也就解释了为什么只执行一次的问题了

通过mountComponent挂载组件,初始化序号,标记等参数,判断是否为无状态组件,并进行对应的组件初始化工作,比如初始化props, context等参数。利用getInitialState获取初始化state,初始化更新队列和更新状态。

若存在componentWillMount,则执行。如果此时在componentWillMount执行setState方法,是不会触发re-render,而是会进行state合并,且inst.state = this._processPendingState(inst.props, inst.context)是在componentWillMount之后执行的。因此componentWillMount中this.state并不是最新的,在render中才可以获取更新后的this.state.

React是利用更新队列this._pendingStateQueue以及更新状态this._pendingReplaceState和this._pendingForceUpdate来实现setState的异步更新机制。

当渲染完成后,若存在componentDidMount,则调用。这就解释了componentWillMount, render, componentDidMount这三者之间的执行顺序。

2. RECEIVE_PROPS

updateComponent负责管理生命周期中的componentWillReceivePropsshouldComponentUpdatecomponentWillUpdaterendercomponentDidUpdate

首先通过updateComponent更新组件,如果前后元素不一致,说明需要进行组件更新。

若存在componentWillReceiveProps则执行。如果此时调用setState是不会触发re-render,而是会进行state合并。且在componentWillReceiveProps、shouldComponetUpdate和componentWillUpdate中也无法获取到更新后的this.state。即此时访问的this.state任然是未更新的数据,需要设置inst.state = nextState后才可以。因此只有在render和componentDidUpdate中才能获取到更新后的this.state.

调用shouldComponentUpdate判断是否需要进行组件更新,如果存在componentWillUpdate则执行。

禁止在shouldComponentUpdate和componentWillUpdate中调用setState,这会造成循环调用,直至耗光浏览器内存

3. UNMOUNTING

unmountComponet负责管理生命周期中的componetWillUnmount。

如果存在componentWillUnmount,则执行并重置所有相关参数,更新队列以及更新状态。

此时调用setState是不会触发re-render的,这是因为所有更新队列和更新状态都被重置为null,并清除了公共类。

深入理解React生命周期

相关推荐