前言
组件的生命周期,以及相关的钩子函数
正文
组件的生命周期:
生命周期是组件从创建到不在运行从页面中卸载掉的整个过程,在整个生命周期中有很多函数会发生运行,这些函数就是钩子函数。只有类组件才会有生命周期。
创建时的钩子函数:
constructor:渲染完成前执行
render:渲染时执行
componDidMount:渲染完成后执行
以上三个函数顺序执行
class App extends React.Component{
constructor(props){
super()
console.log("触发了costructor函数")
}
componentDidMount(){
console.log("触发了componentDidMount函数")
}
render(){
console.log("触发了render函数")
return(
<div>
钩子函数
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'))
值得一提的是当在render中写了setState方法的时候,会出现错误,当state里面的数据被修改之后,会导致页面的重新渲染,render函数就会得到加载,从而再次修改state导致进入无限循环.
更新时的钩子函数:
render:更新时
componentDidUpdate:更新完成后
导致组件更新的三种情况:
1.接收到一个新的参数的时候
2.调用statState更新数据时
3.调用forceUpdate()时更新
this.forceUpdate()
//调用方法会发生更新
class App extends React.Component{
state={
count:0
}
changeClick=()=>{
this.setState({
count:this.state.count+1
})
}
componentDidUpdate(){
console.log("触发了componentDidUpdate函数")
}
render(){
console.log("触发了render函数")
return(
<div>
<button onClick={this.changeClick}>更新state</button>
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'))
不可以在componentDidUpdate函数中单独调用setState方法,否则会导致出现无限循环,加入判断语句即可使用setState。
class App extends React.Component{
state={
count:0
}
changeClick=()=>{
this.setState({
count:this.state.count+1
})
}
//componentDidUpdate函数有两个可选参数分别表示更新前的state,props.
componentDidUpdate(prevProps,prevState){
console.log("旧的state",prevState.count,"新的state",this.state.count)
if(prevState.count !== this.state.count){
this.setState({})
}
console.log("触发了componentDidUpdate函数")
}
render(){
console.log("触发了render函数")
return(
<div>
<button onClick={this.changeClick}>更新state</button>
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'))
一共触发两次,第一次state发生更新,render重新渲染,判断之后调用setState方法再次调用render,之后再调用判断,结束.
卸载时的钩子函数:
componentWillUnmount:当一个组件从页面中清除,常用于清除一些组件创建时创建的东西
class App extends React.Component{
state={
count:0
}
changeClick=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
console.log("触发了render函数")
return(
<div>
<button onClick={this.changeClick}>更新state</button>
{this.state.count>2?<h2>要触发函数了</h2>:<Child number={this.state.count}/>}
</div>
)
}
}
class Child extends React.Component{
componentWillUnmount(){
console.log("触发了componentWillUnmount函数")
}
render(){
return(
<div>
<h2>当前的state的值:{this.props.number}</h2>
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'))
结语
笔者也是第一次学习做出的总结,要是能从我这里得到一些帮助最好不过,若有错误还望大佬在评论帮忙指出。