ReactJS生命周期

2017-07-18  本文已影响0人  风起云帆

The Component Lifecycle
Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with **will
** are called right before something happens, and methods prefixed with **did
** are called right after something happens.

Mounting

These methods are called when an instance of a component is being created and inserted into the DOM:
constructor()

componentWillMount()

render()

componentDidMount()

mount 就是第一次让组件出现在页面中的过程。这个过程的关键就是 render 方法。React 会将 render 的返回值(一般是虚拟 DOM,也可以是 DOM 或者 null)插入到页面中。

这个过程会暴露几个钩子(hook)方便你往里面加代码:

constructor()
componentWillMount()
render()
componentDidMount()

4.jpg

Updating

mount 之后,如果数据有任何变动,就会来到 update 过程,这个过程有 5 个钩子:

1.componentWillReceiveProps(nextProps) - 我要读取 props 啦!

  1. shouldComponentUpdate(nextProps, nextState) - 请问要不要更新组件?true / false
  2. componentWillUpdate() - 我要更新组件啦!
  3. render() - 更新!
  4. componentDidUpdate() - 更新完毕啦!

An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:
componentWillReceiveProps()

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

Unmounting

当一个组件将要从页面中移除时,会进入 unmount 过程,这个过程就一个钩子:

componentWillUnmount() - 我要死啦!
你可以在这个组件死之前做一些清理工作。

This method is called when a component is being removed from the DOM:
componentWillUnmount()

上一篇下一篇

猜你喜欢

热点阅读