随便扯扯React生命周期 --《爱看不看系列》

  生命周期嘛,顾名思义,就是说组件这辈子从生下来到死掉经历的事情。先来看看一张图片,温故温故,如图:react

 

你会发现有些周期的名字都能找出点规律,我找到的规律是凡是 Will 字母的,表示该钩子函数会在该生命周期发生以前调用;包含前缀did表示该钩子函数会在该生命周期发生以后调用。
程序员

 

大概给生命周期分及各种:ajax

一、Mounting(挂载)

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

上面几个函数会在组件被建立和插入到DOM后调用网络

 

二、Updating(更新)

  1. componentWillReceiveProps()
  2. shouldComponentUpdate()
  3. componentWillUpdate()
  4. render()
  5. componentDidUpdate()

props 或者 state 的变化都会致使更新。上面这些方法会在 组件 从新渲染时调用。函数

 

三、Unmounting

  1. componentWillUnmount()

该方法将会在 组件 从DOM中移除时调用this

 

 

分完类以后就来依次说说各个组件是干什么的咯,怕是每一个写react的程序员都会有本身的看法咯。spa

  1. componentWillMount()

这个组件我的以为争议很大,有的人说能够在这个钩子函数内写ajax请求,有的说不行,我仍是保持我本身的观念,code

不能在里面使用setState方法来更新组件,由于它是在render函数以前执行的,也就是说执行它的时候,DOM节点component

是尚未挂在的,强行setState会致使React Component 的 re-render。blog

  2. componentDidMount()

这个函数在组件挂在以后执行的,因此比较适合用做初始化DOM节点的操做和AJAX请求。

在该钩子函数里面,可使用 setState 可是会触发从新渲染 re-render 。 

  3.componentWillReceiveProps(nextProps)

该钩子函数将会在已挂载组件(mounted component)接收到新的 props 以前调用。适用于更新state的值(从新渲染)

比较this.props和nextProps。有一个要注意的地方就是,props即便没有变化,也会调用这个钩子函数,因此,通常咱们的

作法就是比较this.props和nextProps。

  4.shouldComponentUpdate(nextProps, nextState)

当组件接收到新的 Props 或者 state时,要进行 rendering以前会调用 shouldComponentUpdate()。该钩子函数用于告诉 React 组件是否须要从新渲染。

shouldComponentUpdate() 默认返回 true

shouldComponentUpdate() 在两种状况下不会被调用:一、初始化渲染;二、使用了forceUpdate()方法。

可是当 shouldComponentUpdate() 返回 false 的时候,此时 state 发生改变,并不能阻止 child component 进行从新渲染。
可是一旦 shouldComponentUpdate() 返回 false,这就意味着 componentWillUpdate()、 render() 和 componentDidUpdate() 将再也不执行。

 

  5.componentWillUpdate()

state or props 更新后re-render以前调用。
不能在这里调用 setState,若是须要设置 state,应该在 componentWillReceiveProps() 中调用 setState().

 

  6.componentDidUpdate

在组件更新以后立刻调用。在该钩子函数内,你能够:一、操做DOM;二、发起网络请求

 

  7.componentWillUnmount

在组件卸载和销毁前调用。在该钩子函数内能够作一些清除工做,好比:一、取消定时器;二、取消网络请求;三、绑定DOM事件。

相关文章
相关标签/搜索