Fork me on GitHub

React生命周期分析

上图

 

 

 这张图是旧的React生命周期图,从图中可以看出React的生命周期从广义上分为三个阶段:挂载、渲染、卸载

1. 挂载卸载过程

constructor()

  1.子类如果没有 constructor 方法,该方法会被默认添加,即任何的子类都有 constructor 方法,无论定义没定义,它就在那里,不离不弃。

  2.在子类的构造函数 constructor( )中,只有调用 super( )方法之后,才可以使用 this关键字,否则会报错。

      3、组件的初始化,用来定义当前组件所需要的一些状态,状态定义在this.state中。

 

componentWillMount()【当前生命周期在17.0中已经废除掉了】

    1、可以进行前后端数据的请求(在服务端渲染的时候) 
    2、可以在数据第一次被渲染的时候做数据的更改 
    3、在当前生命周期中尽量不要调用this.setState因为当前生命周期函数执行完毕后,会自动执行render函数
    4、可以将外部的数据转换为内部的数据

render:

    1、当前生命周期用来进行数据与模板的结合

    2、render函数第一次执行的时候会将渲染的数据在内存中保存一份,当第二次数据发生了改变后,render会将这次的虚拟DOM与缓存中的虚拟DOM进行对比 这种对比叫做DIFF算法

    3、只要this.state/this.props发生了改变那么render函数就会执行

 

componentDidMount()

    1、当前生命周期我们可以做前后端数据的交互

    2、可以在当前生命周期中获取到真实的DOM  通过this.refs来获取

    3、一般情况下我们都在当前生命周期中做一些插件的实例化


 

2. 更新过程
  • componentWillReceiveProps(nextProps)
  • shouldComponentUpdate(nextProps,nextState)
  • componentWillUpdate (nextProps,nextState)
  • render()
  • componentDidUpdate(prevProps,prevState)
3. 卸载过程
  • componentWillUnmount()

下面我们来讲下每个生命周期的内容

 

1.挂载过程

constructor()

constructor()中完成了React数据的初始化,接收两个参数:props和context,当想在函数内部使用这两个参数时,需使用super()传入这两个参数。
Tips:只要使用了constructor()就必须写super(),否则会导致this指向错误。

componentWillMount()

componentWillMount()一般用的比较少,更多的是在服务端渲染时使用。组件已经在constructor()初始化数据后,但是还未渲染DOM。

componentDidMount()

第一次初始化成功才会进入这个生命周期

组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染

2.更新过程

componentWillReceiveProps (nextProps)【react17删除了】

应用场景:接收到父组件改变后的props需要重新渲染组件

这里接收一个参数接受一个参数nextProps,举个例子:

```

componentWillReceiveProps (nextProps) {
// 对比nextProps和this.props,将nextProps的state为当前组件的state从而重新渲染组件 nextProps.openNotice !== this.props.openNotice&&this.setState({ openNotice:nextProps.openNotice },() => { console.log(this.state.openNotice:nextProps) //将state更新为nextProps,在setState的第二个参数(回调)可以打印出新的state }) }

```

shouldComponentUpdate(nextProps,nextState)【react17删除了】

这个生命周期一般是用于性能优化,这个生命周期是唯一用于控制组件重新渲染。

我们在setState以后,state发生变化,组件会进入重新渲染的流程,在这个生命周期中return false可以阻止组件的更新。

Tips: 父组件的重新渲染会导致其所有子组件的重新渲染,大部分时候我们是不需要所有子组件都跟着重新渲染的,因此可以在子组件的shouldComponentUpdate()生命周期中做判断。

 

componentWillUpdate (nextProps,nextState)【react17删除了】

shouldComponentUpdate返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里可以拿到nextProps和nextState。

render()

render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树。
在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树。
比较以后,找到最小的有差异的DOM节点,并重新渲染。

componentDidUpdate(prevProps,prevState)

每次重新渲染后都会进入这个生命周期,这里可以拿到prevProps和prevState,即更新前的props和state。

 

3.卸载过程

componentWillUnmount ()

组件的卸载和数据的销毁,一般我们会做以下处理:

  1. 清除组建中所有的setTimeout,setInterval
  2. 移除所有组建中的监听 removeEventListener

有时候我们会碰到这个warning:

```

Can only update a mounted or mounting component. This usually      means you called setState() on an unmounted component. This is a   no-op. Please check the code for the undefined component.

```

出现的原因:在组件中的ajax请求返回setState,而你组件销毁的时候,请求还未完成,因此会报warning

解决方法:我们可以在setState前增加一个标识

代码如下:

```

componentDidMount() {
    this.isMount === true
    axios.post().then((res) => {
    this.isMount && this.setState({   // 增加条件ismount为true时
      aaa:res
    })
})
}
componentWillUnmount() {
    this.isMount === false
}

```

再上图

 

 

 

上面这张图是新的React生命周期图,从图中我们可以看到有两个生命周期被新的生命周期替换了:

getDerivedStateFromProps代替了旧的componentWillReceiveProps

getSnapshotBeforeUpdate代替了旧的componentWillUpdate

 

下面我们讲讲这两个新的生命周期,以及为什么要替换旧的那两个生命周期

getDerivedStateFromProps(nextProps, prevState)

代替componentWillReceiveProps()

旧的React中componentWillReceiveProps()方法是用来判断前后两个 props 是否相同,如果不同再将新的 props 更新到相应的 state 上去
这样做会破坏 state 数据的单一数据源,导致组件状态变得不可预测,另一方面也会增加组件的重绘次数。
举个例子:
```
// 旧的react使用componentWillReceiveProps
componentWillReceiveProps(nextProps) {
  if (nextProps.isLogin !== this.props.isLogin) {
    this.setState({ 
      isLogin: nextProps.isLogin,   
    });
  }
  if (nextProps.isLogin) {
    this.handleClose();
  }
}

// 新的react使用getDerivedStateFromProps
static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.isLogin !== prevState.isLogin) {
    return {
      isLogin: nextProps.isLogin,
    };
  }
  return null;
}

componentDidUpdate(prevProps, prevState) {
  if (!prevState.isLogin && this.props.isLogin) {
    this.handleClose();
  }
}
```
componentWillReceiveProps一般做两件事:
1、根据 props 来更新 state
2、触发一些回调,如动画或页面跳转等
 
now:
官方将componentWillReceiveProps更新 state 与触发回调重新分配到了 getDerivedStateFromPropscomponentDidUpdate 中,使得组件整体的更新逻辑更为清晰。
而且在 getDerivedStateFromProps 中还禁止了组件去访问 this.props,强制让开发者去比较 nextProps 与 prevState 中的值,以确保当开发者用到 getDerivedStateFromProps 这个生命周期函数时,就是在根据当前的 props 来更新组件的 state,而不是去做其他一些让组件自身状态变得更加不可预测的事情。

 

getSnapshotBeforeUpdate(prevProps, prevState)

代替componentWillUpdate

componentWillUpdate一般使用场景:

在组件更新前,读取当前某个 DOM 元素的状态,并在 componentDidUpdate 中进行相应的处理。

两者区别

componentWillUpdate:

在 React 开启异步渲染模式后,在 render 阶段读取到的 DOM 元素状态并不总是和 commit 阶段相同,这就导致在
componentDidUpdate 中使用 componentWillUpdate 中读取到的 DOM 元素状态是不安全的,因为这时的值很有可能已经失效了。
 
getSnapshotBeforeUpdate:
getSnapshotBeforeUpdate 会在最终的 render 之前被调用,也就是说在 getSnapshotBeforeUpdate 中读取到的 DOM 元素状态是可以保证与 componentDidUpdate 中一致的。
此生命周期返回的任何值都将作为参数传递给componentDidUpdate()。

 

  

文章就分享到这,欢迎关注“前端大神之路” 

 

posted @ 2020-06-11 16:39  广东靓仔-啊锋  阅读(459)  评论(0编辑  收藏  举报