说到React生命周期,主要指的是类式组件的生命周期,函数式组件是没有生命周期概念的,React类式组件生命周期主要分为三个阶段:挂载阶段、更新阶段、卸载阶段
挂载阶段
这一阶段主要是组件第一次在DOM树中被渲染的过程
constructor 函数
作用:用来通过 props 接收父组件传递过来的数据、通过 this.state 初始化内部的数据、通过 bind 为事件绑定实例
getDerivedStateFromProps 函数(不常用)
作用:state 的值在任何时候都依赖于 props 时使用、该方法返回一个对象来更新 state
render 函数
作用:组件渲染的时候,就会回调
componentDidMount 函数
作用:组件已经挂载到 DOM 上时,就会回调,可以在此阶段发送网络请求、进行一些 DOM 的操作、添加一些订阅等
更新阶段
这一阶段主要是组件状态(state)发生变化,重新更新渲染的过程
getDerivedStateFromProps 函数(不常用)
作用:state 的值在任何时候都依赖于 props 时使用;该方法返回一个对象来更新 state
shouldComponentUpdate 函数
作用:主要用于性能优化,决定是否执行 render 函数
render 函数
作用:组件更新的时候,也会回调
getSnapshotBeforeUpdate 函数(不常用)
作用:在 React 更新 DOM 之前回调的一个函数,可以获取 DOM 更新前的一些信息(比如说滚动位置)
componentDidUpdate 函数
作用:组件已经发生更新时,就会回调,可以在此对更新之后的组件进行操作、对更新前后的props进行比较,也可以在此阶段发送网络请求,反之,则不会执行网络请求
卸载阶段
这一阶段主要是组件从DOM树被移除的过程
componentWillUnmount 函数
作用:组件即将被移除时,就会回调,在此阶段可以执行一些清理的操作,如清除 timer、取消网络请求、清除在 componentDidMount() 中创建的订阅等
代码演示
父组件
// App.jsx
import React from "react"
import Home from "./Home"
class App extends React.Component {
constructor() {
super()
this.state = {
ifShow: true
}
}
changeShow() {
this.setState({ ifShow: !this.state.ifShow })
}
render() {
const { ifShow } = this.state
return (
<div>
<button onClick={e => this.changeShow()}>是否展示</button>
{ ifShow && <Home/> }
</div>
)
}
}
export default App
子组件
// Home.jsx
import React from "react"
class Home extends React.Component {
// 1.构造方法: constructor
constructor() {
console.log("挂载时-创建组件---constructor")
super()
this.state = {
title: "React"
}
}
changeText() {
this.setState({ title: "React学习笔记" })
}
// 2.getDerivedStateFromProps
static getDerivedStateFromProps(props, state){
console.log("挂载或更新时-映射数据---getDerivedStateFromProps");
console.log(props, state)
return props
}
// 3.执行render函数
render() {
if(this.state.title === "React"){
console.log('挂载时-渲染组件---render')
}else{
console.log('更新时-渲染组件---render')
}
const { title } = this.state
return (
<div>
<h1>{title}</h1>
<button onClick={e => this.changeText()}>修改标题</button>
</div>
)
}
// 4.组件被渲染到DOM: 被挂载到DOM
componentDidMount() {
console.log("挂载时-渲染完成---componentDidMount")
}
// 5.组件的DOM被更新完成: DOM发生更新
componentDidUpdate(prevProps, prevState, snapshot) {
// snapshot 可以获取到 getSnapshotBeforeUpdate 函数的返回值
console.log("更新时-更新完成---componentDidUpdate:", prevProps, prevState, snapshot)
}
// 6.组件从DOM中卸载掉: 从DOM移除掉
componentWillUnmount() {
console.log("卸载时-即将被卸载---componentWillUnmount")
}
// 不常用的生命周期补充
shouldComponentUpdate() {
console.log("更新时-决定是否要更新---shouldComponentUpdate")
return true
}
// 获取组件更新前的快照
getSnapshotBeforeUpdate() {
console.log("更新时-最后能获取到更新之前数据的地方---getSnapshotBeforeUpdate")
return {
scrollPosition: 100
}
}
}
export default Home