
| 钩子 函数 | 触发时机 |
|---|---|
| constructor | 创建组件时,最先执行,初始化的时候只执行一次 |
| render | 每次组件渲染都会触发(注意: 不能在里面调用setState() 会陷入死循环) |
| componentDidMount | 组件挂载(完成DOM渲染)后执行,初始化的时候执行一次 |
| componentDidUpdate | 组件更新后(DOM渲染完毕) |
| componentWillUnmount | 组件卸载(从页面中消失) |
注意:只有类组件才有生命周期
组件挂载完成渲染class App extends Component {
constructor() {
super()
console.log("1.constructor")
}
componentDidMount () {
console.log("3.componentDidMount")
}
render () {
console.log("2.render")
return (
生命周期测试
)
}
}
React 在 开发环境下会刻意执行两次渲染,以防止组件内有什么 side effect 引发 bug,提早预防。这里官方github上有做出解释:
组件更新时的生命周期class App extends Component {
state = {
count: 0
}
UpdateData = () => {
this.setState({
count: this.state.count + 1
})
}
componentDidUpdate () {
//组件更新时触发
console.log("componentDidUpdate")
}
render () {
return (
生命周期测试
)
}
}
组件卸载的生命周期
class SonA extends Component {
componentWillUnmount () {
//组件被卸载时触发
console.log("componentWillUnmount")
}
render () {
return (
组件卸载测试
)
}
}
class App extends Component {
state = {
count: 0,
onoff: true
}
UpdateData = () => {
this.setState({
count: this.state.count + 1,
onoff: !this.state.onoff
})
}
render () {
console.log("2.render")
return (
生命周期测试
{this.state.onoff ? : ""}
)
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)