React生命周期三个阶段
- 装载阶段(Mounting):构建并插入真实DOM
- 更新阶段(Updating):更新数据重新渲染DOM
-
销毁阶段(Unmounting):移除真实DOM
React中文网生命周期图
一、装载阶段(Mounting)
装载阶段主要包括以下几个函数
constructor
- 组件的构造函数
- 通常在这里初始化组件内部状态(state)
- 如果要调用this必须要super()之后
constructor() { // 只执行一次,且this在super()执行完成之后才能调用 super() console.log('constructor只执行一次'); this.state = { name: 'zs' } }
componentWillMount
-
组件将要挂载到虚拟DOM之前执行
-
唯一一个可以同步修改state的生命周期函数
注意点1:将在 react 17这个版本之后废弃,如果还想继续用, 可以用UNSAFE_componentWillMount来代替。
注意点2:不要在这个方法里进行ajax请求,因为在react 新的版本采用了fiber算法
fiber算法是异步渲染,异步的渲染,有可能随时中断,那么componentWillMount就可能执行多次,由此可以想到ajax请
求也有可能会执行多次。UNSAFE_componentWillMount () { console.log('componentWillMount执行,dom挂载之前') }
static getDerivedStateFromProps
- react 16.3之后新增的生命周期
- 是一个静态方法
- 静态方法中没有this
- 接收参数为下一次传入的props
- 完成后需要返回一个对象,该对象就相当于setState的参数
static getDerivedStateFromProps (nextProps) { console.log('getDerivedStateFromProps, return对象改变state') return { status: nextProps.isCompleted ? '已完成' : '未完成' } }
注意:如果使用了getDerivedStateFromProps 方法,那么componentWillMount、componentWillReceiveProps、componentWillUpdate三个方法都将无效并报错
render
- 生成虚拟DOM,此时并没有实际DOM
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
- 渲染真实DOM
- 在此发送ajax请求
componentDidMount () {
console.log('componentDidMount, 真实dom挂载完成')
// 此时渲染完成真实DOM,在此请求ajax
}
二、更新阶段(Updating)
更新阶段分为两种情况:state改变和props改变
- state改变:执行shouldComponentUpdate
- props改变:先执行componentWillReceiveProps再执行shouldComponentUpdate
componentWillReceiveProps
- 16.4之前,由于在更新阶段,没有static getDerivedStateFromProps这个方法,如果有根据props来改变state,就需要在这再重新设置1次
- componentWillReceiveProps在react 17 版本中将要被废弃
componentWillReceiveProps () {
console.log('执行componentWillReceiveProps, 更新props')
// static getDerivedStateFromProps出现之前进行接收新的props设置给state
}
shouldComponentUpdate
- 用于react的性能优化(判断是否需要重新渲染)
- 接收两个参数(nextProps, nextState)
- 返回值为Boolean类型(true为重新渲染,false不重新渲染)
shouldComponentUpdate (nextProps, nextState) {
console.log('重绘dom----shouldComponentUpdate,主要在这里做性能优化')
return nextProps.isCompleted !== this.props.isCompleted
// 返回值true为重新渲染,false不重新渲染
}
componentWillUpdate
- componentWillUpdate在react 17 版本中将要被废弃
componentWillUpdate () {
console.log('componentWillUpdate执行完成之前的方法,将要更新,之后执行render渲染虚拟dom');
// 该方法在17版本之后会被废弃
}
render
- 与上文的render方法相同
componentDidUpdate
- 根据更新次数更新多次
componentDidUpdate () {
console.log('componentDidUpdate表明数据更新完成');
// 数据更新完成会调用该方法,因此可能多次调用
}
三、销毁阶段
componentWillUnmount
- 组件将要销毁
- 清理定时器,解绑事件
componentWillUnmount () {
console.log('组件马上销毁之前');
// 此处清理定时器,解绑事件
}
网友评论