React生命周期

2019-02-27  本文已影响0人  MangoLx

React生命周期三个阶段


一、装载阶段(Mounting)

装载阶段主要包括以下几个函数

constructor

componentWillMount

static getDerivedStateFromProps

render

render () {
  console.log('执行render,合成虚拟dom')
  // 此时没有真实DOM
  return (
    <li>
      {this.props.children}------
      <span>{this.state.status}</span>------
      <button onClick={this.handleChangeItem}>{this.props.isCompleted ? '重做' : '完成'}</button>------
      <button onClick={this.handleDelItem}>删除</button>
    </li>
  )
}

componentDidMount

componentDidMount () {
  console.log('componentDidMount, 真实dom挂载完成')
  // 此时渲染完成真实DOM,在此请求ajax
}

二、更新阶段(Updating)

更新阶段分为两种情况:state改变和props改变

componentWillReceiveProps

componentWillReceiveProps () {
  console.log('执行componentWillReceiveProps, 更新props')
  // static getDerivedStateFromProps出现之前进行接收新的props设置给state
}

shouldComponentUpdate

shouldComponentUpdate (nextProps, nextState) {
  console.log('重绘dom----shouldComponentUpdate,主要在这里做性能优化')
  return nextProps.isCompleted !== this.props.isCompleted
  // 返回值true为重新渲染,false不重新渲染
}

componentWillUpdate

componentWillUpdate () {
  console.log('componentWillUpdate执行完成之前的方法,将要更新,之后执行render渲染虚拟dom');
  // 该方法在17版本之后会被废弃
}

render

componentDidUpdate

componentDidUpdate () {
  console.log('componentDidUpdate表明数据更新完成');
  // 数据更新完成会调用该方法,因此可能多次调用
}

三、销毁阶段

componentWillUnmount

componentWillUnmount () {
  console.log('组件马上销毁之前');
  // 此处清理定时器,解绑事件
}
上一篇下一篇

猜你喜欢

热点阅读