简述React的生命周期

506 阅读2分钟

React生命周期

同Vue一样React也有自己的生命周期,在官方给出的说明中主要分为三大类Mount(装载)、更新(Update)以及移除(Unmount)三个主要生命周期。

  • Mount主要分为constructor、componentWillMount、render以及componentDidMount,
  • Update主要分为componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render以及componentDidUpdate
  • Unmount主要分为componentWillUnMount

一、Mount

1.constructor

初始化state,也可以添加bind一类的方法。

constructor(props) {
    super(props)//此处super()必须存在,否者浏览器会报错
    this.state = {
        data: new Data()    
        ……
    }
    ……
} 

2.componentWillMount

在16版本之前可以直接使用componentWillMount(),在17及17以后版本改为UNSAFE_componentWillMount()。 componentWillMount() 组件将要Mount,但还未进行Mount。这里是惟一一个可以直接同步修改state并且在页面正确渲染的地方。可能不止运行一次,但很多人认为是只运行一次,所以很多人想在这个地方做ajax请求,但官方表示将会废弃。

3.render

构建虚拟DOM

4.componentDidMount

在这里获取到真实的DOM,如果要使用第三方的dom框架,应该在这里去初始化,React里一般都在这里做ajax,componentDidMount只会执行一次,有数据返回后去setState,将会执行到update阶段。

二、Update

1.componentWillReceiveProps(针对props有改变)

在16版本之前可以直接使用componentWillReceiveProps(),在17及17以后版本改为UNSAFE_componentWillReceiveProps()。 如果在constructor里面,有通过props来生成state,这里也得做同样的操作。在这里的this.props还是原来的。

2.shouldComponentUpdate(官方说明中唯一优化React的地方)

shouldComponentUpdate(nextProps, nextState)惟一一个做react性能优化的生命周期,必须! 返回一个布尔值。 如果是false,就不会再往下执行。

一般会根据nextProp VS this.props 或者 nextState VS this.state去判断返回true还是false。

shouldComponentUpdate

3.componentWillUpdate

在16版本之前可以直接使用componentWillUpdate(),在17及17以后版本改为UNSAFE_componentWillUpdate()。

4.componentDidUpdate

componentDidUpdate()真实的dom已经更新到页面上

三、Unmount

1.componentWillUnMount

在componentWillUnMount()中去清空定时器一类的东西。

四、新增生命周期

static getDerivedStateFromProps(props, state)

static getDerivedStateFromProps(props, state) {
  在这里没有this
  需要return 一个对象
}

不管是mount还是update阶段都会执行

五、旧版本

在早期(16及1以前6版本)使用createClass()可以得到两个周期。

createClass({
    这里面可以有getDefaultProps(新版里直接在class里写static defaultProps = {})和getInitialState(新版直接在constructor里写this.state={}或者直接在class里写 state ={})两个生命周期
  })

createClass