React生命周期
随着react版本的变化,react生命周期也做了一些调整,整体来说,有3个生命周期函数最为重要:
componentDidMount
componentWillUpdate
componentWillUnmount
精简图:
详图:
来看下面这个demo:
import React, { PureComponent } from 'react'
export default class Test extends PureComponent {
constructor(props){
super(props)
this.state = {
count: 0
}
console.log("constructor")
}
componentDidMount(){
console.log("componentDidMount")
}
componentWillUnmount(){
console.log("componentWillUnmount")
}
componentDidUpdate(){
console.log("componentDidUpdate")
}
render() {
console.log("render")
const { count } = this.state
return (
<div>
<h3>count: {count}</h3>
<button onClick={()=>this.setState({count:count+1})}>add 1</button>
</div>
)
}
}
当页面第一次挂载的时候:
点击add 1
:
当组件即将取消挂载的时候,会触发componentWillUnmount
- 可以在路由切换的时候看到效果
注意
所有的生命周期函数都可以不写 但是唯独render不可省
原因是:组件继承了 Ract.Component
,Ract.Component
定义了所有生命周期函数,唯独没有定义render,所以render需要开发者自己去实现