生命周期:一个组件从开始到消亡所经历的各种状态。
生命周期函数:组件从被创建,被挂载到页面,页面关闭被卸载等各个阶段伴随着各种的事件,这些事件就被称为生命周期函数。
通过声明周期函数可以让开发者的代码参与到组件的声明周期中,这样开发者就可以控制组件的行为。
React组件的生命周期包含三个阶段:创建阶段(Mounting)、运行和交互阶段(Updating)、卸载阶段(Unmounting)。
创建阶段(Mounting):该阶段函数只执行一次
getDefaultProps:只调用一次,实力之间共享引用
getInitialState:初始化每个实例特有的状态
constructor():获取props,初始化state
class Greeting extends React.Component {
constructor(props) {
// 获取 props
super(props)
// 初始化 state
this.state = {
count: props.initCount
}
}
}
// 初始化 props
// 语法:通过静态属性 defaultProps 来初始化props
Greeting.defaultProps = {
initCount: 0
};
componentWillMount():组件被挂载之前调用,在render()之前调用,所以同步状态不会重新渲染,无法获取DOM对象,可以通过setState()方法改变状态值,常用于发送ajax请求
componentWillMount() {
console.warn(document.getElementById('btn')) // null
this.setState({
count: this.state.count + 1
})
}
render():将组件渲染到页面中时调用,注意此时是进行时,组件尚未完全渲染到页面,因此无法获取页面的DOM对象,不要在此函数中调用setState(),否则会造成递归渲染,因为状态改变会重新调用render()函数。
render() {
console.warn(document.getElementById('btn')) // null
return (
<button>打豆豆一次</button>{this.state.count}
)
}
componentDidMount():组件已全部挂载到页面中,可以获取DOM,可以发送请求获取数据,可以通过setState()修改状态值,这里修改状态会触发人render()重新渲染
componentDidMount() {
// 此时,就可以获取到组件内部的DOM对象
console.warn('componentDidMount', document.getElementById('btn'))
}
运行和交互阶段(Updating):该阶段函数执行多次,每当组件的props或state改变,都会出发运行该阶段的函数。
componentWillReceiveProps():组件接收到新的props前触发,参数是新的props,可以通过this.props获取上一次的值,修改state不会触发该方法
componentWillReceiveProps(nextProps) {
// 可以通过对比this.props和nextProps并在该方法中使用this.setState()处理状态改变
console.warn('componentWillReceiveProps', nextProps)
console.warn('componentWillReceiveProps', this.props)
}
shouldComponentUpdate():根据这个方法的返回值true/false决定是否重新渲染组件,如果返回false后续的render()不会被调用。通过某个条件渲染组件,降低组件的渲染频率,提升组件性能。
// - 参数:
// - 第一个参数:最新属性对象
// - 第二个参数:最新状态对象
shouldComponentUpdate(nextProps, nextState) {
console.warn('shouldComponentUpdate', nextProps, nextState)
return nextState.count % 2 === 0
}
componentWillUpdate():组件将要更新,参数是最新的属性和状态对象,不能修改状态,否则会循环渲染。
componentWillUpdate(nextProps, nextState) {
console.warn('componentWillUpdate', nextProps, nextState)
}
render():重新渲染组件,和Mounting阶段的render()是同一个函数。这个函数可以执行对此,只要组件的属性或状态改变了,就会调用该函数。
componentDidUpdate():组件更新完成后调用,参数是旧的属性和状态对象。
componentDidUpdate(prevProps, prevState) {
console.warn('componentDidUpdate', prevProps, prevState)
}
卸载阶段(Unmounting):该阶段函数只执行一次
componentWillUnmount():卸载组件前调用,常用于清理工作,如:清除定时器,清除componentDidMount创建的DOM对象等