import React from 'react'
// 三个阶段:装载阶段(3)、更新阶段(2)、销毁阶段(1)
export default class LifeDemo extends React.Component {
// 装载阶段(3)
// 执行顺序:constructor / render / componentDidMount
// 构造器
// super 必须是第一行代码,声明式变量定义在 this.state 中
// 在构造器中,props 和 state 不要交叉,他俩没有任何关系
// 在构造器中,不要执行 this.setState()
// 在构造器中,不要开启异步任务,比如调接口、定时器等
constructor(props) {
super(props)
this.state = {
count: 1,
flag: false
}
}
// 相当于 Vue 中的 mounted()
// 表示 DOM 初始化已经完成,所有虚拟 DOM 都已经被渲染成真实 DOM 了
// 一般在这里,可以调接口、定时器、DOM 操作
componentDidMount() {
console.log('------------componentDidMount')
}
// 更新阶段(2)
// 执行顺序:shouldComponentUpdate / componentDidUpdate
// 这是一个开关:用于控制是否更新
// 这个生命周期,用于性能优化,可以精确控制某些state变量发生变化时不更新视图
// 实际工作中很少用,我们会用函数式组件(PureComponent)作为替代解决
shouldComponentUpdate(nextProps, nextState) {
console.log('------------shouldComponentUpdate')
console.log('开关打开state', nextState)
let { flag } = this.state
return (nextState.flag === flag && nextState.count <= 10)
}
// 相当于 Vue 中的 update
// 表示 DOM 已经更新完成
// 在该生命周期中,同样不要使用 this.setState()
componentDidUpdate() {
console.log('------------componentDidUpdate')
}
// 销毁阶段(1)
// 相当于Vue中的beforeDistroy
// 关闭长连接、定时器,清缓存
componentWillUnmount() {
console.log('------------componentWillUnmount')
}
// render() 非常特殊
// 它是React类组件中唯一的一个必须的生命周期
// 它在装载阶段和更新阶段都会运行
// 当 state 发生变化时,render 执行二次渲染,是根据 diff 运算的脏节点来更新界面,不是全部更新
// 在render的return之前可以进行业务逻辑操作
// 在render中或者自定义的渲染函数中,不能使用 this.setState()
render() {
let { count, flag } = this.state
console.log('------------render')
return (
<div>
<h1>测试生命周期</h1>
<hr />
<h2>{count}</h2>
<button onClick={() => this.setState(state => ({ count: state.count + 1 }))}>改变count(当count大于10时,不更新)</button>
<button onClick={() => this.setState(state => ({ flag: !state.flag }))}>改变flag(永远不触发视图更新)</button>
</div>
)
}
}
React 常见的生命周期
最新推荐文章于 2025-07-03 11:43:38 发布