Vue.js中组件有如下生命周期函数:
beforeCreate / craeted / beforeMount / mounted / beforeUpdate / updated / beforeDestroy / destroyed
小程序中组件有如下生命周期函数:
onLoad / onShow / onReady / onHide / onUnload
uni-app中有如下生命周期函数:
应用级: onLaunch / onShow / onHide
页面级: 同小程序
组件级: 同Vue.js
React中的生命周期钩子函数(不同版本的区别很大)
以React v17.0.2版为例
挂载
compoentDidmount()----组件挂载完成
更新
shouldComponentUpdate()----每次数据变化后组件更新前进行的疑问
componentDidUpdate()----组件完成更新
卸载
componentWillUnmount()----组件即将卸载
以下方代码为例
src/App.js
import React, { Component } from 'react'
import ClickCounter from './components/Child'
export default class App extends Component {
state={
showChild:true, //是否显示子组件
}
_change=(e)=>{
this.setState({showChild:e.target.checked})
}
render() {
return (
<div>
<h2>这里是根组件App</h2>
<input checked={this.state.showChild} onChange={this._change} type="checkbox"/>显示子组件吗?
<hr/>
{this.state.showChild&&<ClickCounter/>}
</div>
)
}
}
src/components/Child.js
import React, { Component } from 'react'
export default class Child extends Component {
state={
count:0
}
constructor(p){
super(p)
console.log('=====constructor 组件创建出来了=====')
}
componentDidMount(){
console.log('=====componentDidMound 组件完成挂载=====')
}
shouldComponentUpdate(){
console.log('=====shouldComponentUpdate 组件应该更新吗=====')
let c=this.state.count+1
console.log(c)
return true
}
componentDidUpdate(){
console.log('=====componentDidUpdate 组件完成更新=====')
}
componentWillUnmount(){
console.log('=====WillUnmount 组件即将销毁=====')
}
_doClick=()=>{
this.setState({count:this.state.count+1})
}
render() {
return (
<div>
<button onClick={this._doClick}>目前已经点击{this.state.count}次</button>
</div>
)
}
}
运行出来的效果如下如所示
复选框选中后如上图所示,子组件会渲染出来
如果未选中,如下图所示,子组件不会渲染,如下图所示
当然 我在代码中设置的默认为选中状态,当进入页面时会直接执行函数constructor()和componentDidMount()
控制台打印结果如下图
当我们点击按钮时,次数会加1,然后会执行函数shouldComponentUpdate(),
当此函数执行完之后,如果函数返回true,会继续执行函数componentDidUpdate()
打印结果如下图
如果函数shouldComponentUpdate()执行完后的返回值为false,则不会继续执行函数componentDidUpdate(),
打印结果如下图
可以看到,此时,数据会发生修改,但是没有渲染到页面上,所以按钮中显示的还是0次
当我们取消复选框的选中状态时,会执行函数componentWillUnmount(),此时组件会销毁,如图
这就是我对react生命周期函数的理解,可能还有什么地方没有说到,如果发现的话可以发评论,我看到的话会继续改进的