React 类组件的生命周期,就是组件从创建到消耗的过程
只有类组件才有生命周期,分为 挂载阶段、更新阶段、卸载阶段
挂载阶段
钩子函数
constructor 创建组件时,最先执行
作用:初始化 state ,创建 Ref ,使用 bind 解决 this 指向
render 每次组件渲染都会触发
作用: 渲染UI (不能调用 setState())
componentDidMount 组件挂载后(完成DOM渲染)
作用: 发送网络请求,DOM操作
import { Component } from 'react'
export default class App extends Component {
constructor () {
super()
console.log('1. constructor执行')
}
componentDidMount () {
console.log('3. componentDidMount执行')
}
render() {
console.log('2. render执行')
return <div>App组件</div>
}
}
更新阶段
触发
- setState()
- forceUpdata() 强制组件更新
- 组件接收到新的props
钩子函数
render 每次组件渲染都会触发
作用: 渲染UI (不能调用 setState())
componentDidUpdate 组件更新后(完成DOM渲染)
作用:DOM操作,可以获取到更新后的DOM内容,不要直接调用setState
import { Component } from 'react'
class Child extends Component {
render() {
return <h1>统计豆豆被打的次数:</h1>
}
}
export default class App extends Component {
state = {
count: 0
}
handleClick = () => {
this.setState({
count: this.state.count + 1
})
}
componentDidUpdate() {
console.log('2. componentDidUpdate执行')
}
render() {
console.log('1. render执行')
return (
<div>
<Child />
<button onClick={this.handleClick}>打豆豆</button>
</div>
)
}
}
卸载阶段
在组件被移除的时候(消失)触发卸载阶段
钩子函数
componentWillUnmount 组件卸载(从页面中消失)
作用:执行清理工作(清理定时器等
import { Component } from 'react'
class Child extends Component {
componentWillUnmount () {
console.log('componentWillUnmount执行')
}
render() {
return <h1>统计豆豆被打的次数:{this.props.count}</h1>
}
}
export default class App extends Component {
state = {
count: 0
}
handleClick = () => {
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
{ this.state.count < 5 && <Child count={this.state.count} />}
<button onClick={this.handleClick}>打豆豆</button>
</div>
)
}
}
)