React生命周期

159 阅读3分钟

React的生命周期从广义上分为三个阶段:挂载、渲染、卸载

因此可以把React的生命周期分为两类:挂载卸载过程和更新过程。 React的生命周期图:

React生命周期图解
React生命周期图解

新建LifeCyclePage.js来演示:

import React, {Componentfrom 'react'
import PropsTypes from 'prop-types'
export default class LifeCyclePage extends Component {
  static defaultProps {
    msg'omg' // 默认的props
  }
  static propTypes = {
    msgPropsTypes.string.toRequired
  }
  constructor(props) {
    super(props)
    this.state = {
      count0
    }
  }
}

1 componentWillMount

将要装载,在render之前调用。

每一个组件render之前立即调用。

已经被废弃了,如果想继续使用,前面加UNSAFE_才可以

2 getDerivedStateFromProps

执行顺序: constructor之后,render之前被调用

  • 前面加static使用,且每次在render之前被调用

  • 初次挂载和后续更新都会被调用,可与componentWillReceiveProps形成对比,(后者初次挂载不触发,仅在父组件重新渲染时触发,而不是内部调用state)

  • 它可以返回一个对象更新state,返回null则不更新

static getDerivedStateFromProps (props, state) {
  const { count } = state
  // 返回一个对象来直接修改state, 返回null则不更新
  return count > 5  ? {count: 0} : null
}

3 componentDidMount

装载完成,在render之后调用

render之后并不会立即调用,而是所有的子组件都render完之后才可以调用

4 shouldComponentUpdate

可以进行性能优化

shouldComponentUpdate(nextProps, nextState) {
  const {count} = nextState
  // 如果返回true,则可更新组件,如果返回false,则组件不再更新。
  // 用来优化性能
  return count ! == 3
}

5 componentWillUpdate

组件将要更新数据时触发的函数,参数如下:

  • newProps   新的props
  • newState   新的State
  • newContext 新的context

同样被弃掉了,同上面的componentWillMount,要想使用加UNSAFE_

6 getSnapShotBeforeUpdate

  • 在render之后,componentDidUpdate之前被调用

  • return 的数据可以作为componentDidUpdate的参数

getSnapShotBeforeUpdate(prevprops, prevState) {
  console.log(prevprops, prevState)
  return {
    msg'jgz'
  }
}

7 componentDidUpdate

componentDidUpdate(prevprops, prevState, snapshot) {
  // 三参数均是getSnapShotBeforeUpdate传来的参数
  console.log()
}

代码

setCount = () => {
  this.setState{
    countthis.state.count + 1
  }
}
render() {
  const {count} = this.state
  return (
    <div>
      <h3>LifeCyclePage</h3>
      <p>{count}</p>
      <button Onclick={this.setCount}>改变count</button>
      <Child count={count} />
    </div>
  )
}

8 componentWillReceiveProps

class Child extends Component {
  componentWillReceiveProps(nextProps) {
    // 参数是接收新的props
    // 16.3之后被弃用了,同上面那两个相同
  }
}

9 componentWillUnmount

取消订阅时候使用

class Child extends Component {
  componentWillReceiveProps(nextProps) {
    // 参数是接收新的props
    // 16.3之后被弃用了,同上面那两个相同
  }
  componentWillUnmount(){}
    render() {
      const {count} = this.props
      return <div>Child, {count}</div>
    }
}

综上: React16.3之后被废弃的三个生命周期:

  • componentWillMount
  • componentWillUpdate
  • componentWillReceiveProps

新加的声明周期:

  • getDerivedStateFromProps
  • getSnapShotBeforeUpdate