React
每个组件都包含生命周期方法,这些方法会在特定的阶段进行调用,如下图
这里说的组件是指类组件
挂载时
constructor
组件进行实例化时会执行该构造函数,如果不进行state
的初始化或事件的绑定也可以不实现
也就是使用了该组件就会调用
render
页面就行渲染就会调用
无论是初始化渲染还是因为
state
或props
发生了改变
componentDidMount
组件成功挂载到DOM
树上时进行调用,可以在该周期函数中进行发送网络请求或添加订阅等一些操作
// App.jsx
import About from "./components/About"
import React, { Component } from "react"
class App extends Component {
render() {
return (
<div>
App
<About />
</div>
)
}
}
// About.jsx
import React, { Component } from "react"
class About extends Component {
constructor() {
super()
console.log("constructor")
}
render() {
console.log("render")
return <h1>About</h1>
}
componentDidMount() {
console.log("挂载完成")
}
}
export default About
更新时
componentDidUpdate
组件发生更新时调用,首次渲染不会执行,在必要条件下也可以在该周期函数中发送网络请求
// App.jsx 同上
// About.jsx
import React, { Component } from "react"
class About extends Component {
constructor() {
super()
this.state = {
name: "sakurige",
}
console.log("constructor")
}
changeName() {
this.setState({
name: "羽苏",
})
}
render() {
const { name } = this.state
console.log("render")
return (
<div>
<h1>About {name}</h1>
<button onClick={() => this.changeName()}>Change Name</button>
</div>
)
}
componentDidMount() {
console.log("挂载完成")
}
componentDidUpdate() {
console.log("更新完成")
}
}
export default About
在About.jsx
中增加了一个state
以及一个按钮用于改变state
,在初始状态下,同样是constructor``render``componentDidMount
进行了调用,可见componentDidUpdate
在首次渲染是不会执行的
点击按钮更新数据,render
与componentDidUpdate
执行
卸载时
componentWillUnmount
组件卸载前调用,可以在该会调中进行一些清理操作,如清理定时器,取消网络请求以及移除之前添加的订阅等
// App.jsx 添加一个移除展示 About的按钮
class App extends Component {
constructor() {
super()
this.state = {
isShow: true,
}
}
changeShow() {
this.setState({
isShow: !this.state.isShow,
})
}
render() {
const { isShow } = this.state
return (
<div>
App
{/* 根据 isShow的值判断是否移除 About */}
{isShow ? <About /> : ""}
<button onClick={() => this.changeShow()}>show</button>
</div>
)
}
}
// About.jsx 添加 componentWillUnmount 函数
componentWillUnmount() {
console.log("将要被卸载了")
}
初始化时效果同上,点击切换按钮时触发 componentWillUnmount
其他生命周期函数
shouldComponentUpdate
根据返回值判断组件是否应该更新,true
则更新,false
不更新。上面componentDidUpdate
,在第一次变化之后,如果再点击按钮state
是不会发生变化的,但是componentDidUpdate
依旧会进行回调,这时候可以通过该函数来判断一下
shouldComponentUpdate(nextProps, nextStates) {
// 比较下一个 state 与 这一次的state是否相同
return nextStates.name !== this.state.name
}
仅作为性能优化存在。不要依赖它来阻止渲染,也不建议深度检查,如果要进行相关优化建议使用内置的
PureComponent