第一步:初始化阶段
即(constructor
) 继承了基类,才会有render() 方法,生命周期才能使用。
其中super()
,用来调用基类的构造方法,将父组件的props注入子组件【props只读,不可变;state可变】
1.组件在使用时,先进入构造函数constructor。做了什么
-
在构造函数主要通过super()访问父类React.Component的构造函数,要把props形参传递到父类React.Component中,让父类React.Component去初始props的默认值以及props的数据类型。
-
初始化当前组件的state,纠正事件中的this,等等
第二步:挂载阶段
即componentWillMount()
componentWillMount()
仅在render()
方法前被调用一次,如果在该方法中调用了setState方法去改变组件的状态值,那么调用render()后,将会直接看到改变过了的状态值,并且不论状态值怎么改变,componentWillMount()都不会再被调用。
但在最新的react我们发现该方法已被弃用
第三步:组件更新阶段
render()
setState引起的state更新、父组件重新render引起的props更新,更新后的state、props无论是否有变化都会引起子组件重新更新render
这里可以用shouldComponentUpdate()
来优化
合适获取数据更为合适?
组件开始渲染,一般情况组件开始渲染时要提供好数据,觉得在componentWillMount获取数据合适。最合适的获取数据的地方componentDidMount。因为获取数据后会更改state,如果state发生变化,render默认会重新执行
componentDidMount()
件挂载到DOM后调用,方法会在组件已经被渲染到 DOM 中后运行,只会调用一次!
shouldComponentUpdate()
返回true继续执行,false阻止组件更新,减少不必要的渲染,优化性能;就算上一个方法执行了this.state更新了state,但在render之前此方法中的this.state依然指向更新之前的!!!,否则就永远是true了;
componentWillUpdate()
在render之前执行,进行更新前的操作,比较少用;
componentDidUpdate
此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState指组件更新前的props和state
第四步:卸载阶段
componentWillUnmount()
在组件被卸载前调用,可以执行一些清理工作,如清除定时器,清除挂载后手动创建的DOM,避免内存泄漏。
源码如下
import React from 'react'
export default class ComSix extends React.Component{
constructor(props){
super(props)
console.log("1.组件在使用时,先进入构造函数constructor。做了什么:1.在构造函数主要通过super()访问父类React.Component的构造函数,要把props形参传递到父类React.Component中,让父类React.Component去初始props的默认值以及props的数据类型。2. 初始化当前组件的state,纠正事件中的this,等等")
this.state = {
count: 10
}
}
changeCount(){
this.setState({
count: this.state.count + 1
})
}
componentWillMount(){
console.log('2. 组件即将准备好,已被废弃');
}
render(){
console.log('3. 组件开始渲染,一般情况组件开始渲染时要提供好数据,觉得在componentWillMount获取数据合适。最合适的获取数据的地方componentDidMount。因为获取数据后会更改state,如果state发生变化,render默认会重新执行')
return (
<div style={{border:'2px solid blue',margin:'20px 0',padding:'20px 0'}}>
<h1>演示生命周期{this.props.msg}-{this.state.count}</h1>
<button onClick={()=>{this.changeCount()}}>更改count</button>
</div>
);
}
componentDidMount(){
console.log("4. 组件完全准备好,虚拟DOM结构生成。")
}
componentWillReceiveProps(){
console.log("5. 不会执行,废弃了")
}
shouldComponentUpdate(){
console.log("6. 组件是否重新渲染?返回true,执行render(),返回false,不执行render()")
return true;
}
componentWillUpdate(){
console.log("7.数据发生变化时,组件即将更新")
}
componentDidUpdate(){
console.log('8.数据发生变化时,组件更新完成')
}
componentWillUnmount(){
console.log('9.组件销毁前执行,路由切换时可以看到效果。')
}
}