React生命周期函数详解

React生命周期函数详解

React的生命周期主要有3个过程

  • 装载过程 Mount 组件第一次在DOM中渲染
  • 更新过程 Update 组件重新渲染
  • 卸载过程 UnMount 组件从DOM中移除

装载过程

  • constructor

    初始化,绑定this

  • getInitialState (React.createClass)

    初始化state

  • getDefaultProps (React.createClass)

    初始化props

  • componentWillMount

    很少使用这个,因为这里setState也不会导致重新渲染,这里的事情可以在构造函数中完成

  • render

    render应该是一个纯函数,完全根据state和props来决定返回结果,而不产生副作用,所以render中调用setState是错的,因为纯函数不应该引起状态的改变

  • componentDidMount

    这个函数调用的时候render函数已经把JSX渲染好了,一般来说我们的请求都是在这个函数中来调用

更新过程

  • componentWillReceiveProps

    只要是父组件的render函数被调用,在render里渲染的子组件就会经历更新过程,不管父组件传递给子组件的props有没有改变,都会触发componentWillReceiveProps

  • shouldComponentUpdate

    应该是除了render之外最重要的函数了。它决定了一个组件什么时候需不需要渲染。
    render和shouldComponentUpdate是React中唯二需要有返回值的函数,shouldComponentUpdate返回一个布尔值,告诉React是否需要继续更新,若为true则继续,为false则停止更新,不会触发之后的重新渲染

  • componentwillUpdate

    即将render的时候执行

  • render
  • componentDisUpdate
    组件渲染完毕后执行

卸载过程

  • componentWillUnmount

猜你喜欢

转载自blog.csdn.net/lihangxiaoji/article/details/79959701