前言
生命周期概念广义来说生命周期泛指自然界和人类社会中各种客观事物的阶段性变化及其规律在 React 框架中则用来描述组件挂载更新卸载三个阶段。
其中,每个阶段又分为几个不同的小阶段:
- 组件将要挂载时触发的函数:componentWillMount
- 组件挂载完成时触发的函数:componentDidMount
- 是否要更新数据时触发的函数:shouldComponentUpdate
- 将要更新数据时触发的函数:componentWillUpdate
- 数据更新完成时触发的函数:componentDidUpdate
- 组件将要销毁时触发的函数:componentWillUnmount
- 父组件中改变了props传值时触发的函数:componentWillReceiveProps
一、挂载
- constructor(): 在 React 组件挂载之前,会调用它的构造函数。
- getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用
- render(): render() 方法是 class 组件中唯一必须实现的方法。
- componentDidMount(): 在组件挂载后(插入 DOM 树中)立即调用。
render() 方法是 class 组件中唯一必须实现的方法,其他方法可以根据自己的需要来实现。
码来:
import React ,{Component} from 'react'
class Dyw extends Component{
constructor(props){
console.log('01构造函数')
super(props)
this.state={
}
}
//组件将要挂载时候触发的生命周期函数
componentWillMount(){
console.log('02组件将要挂载')
}
//组件挂载完成时候触发的生命周期函数
componentDidMount(){
console.log('04组件将要挂载')
}
render(){
console.log('03数据渲染render')
return(
<div>
生命周期函数演示
</div>
)
}
}
export default Dyw
二、更新
每当组件的 state 或 props 发生变化时,组件就会更新。
当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
1.getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。
2.shouldComponentUpdate():当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。
3. render(): render() 方法是 class 组件中唯一必须实现的方法。
4. getSnapshotBeforeUpdate(): 在最近一次渲染输出(提交到 DOM 节点)之前调用。
5. componentDidUpdate(): 在更新后会被立即调用。
上码:
import React ,{Component} from 'react'
class Dyw extends Component{
constructor(props){
super(props)
this.state={
msg:'我是一个msg数据'
}
}
//是否要更新数据,如果返回true才会更新数据
shouldComponentUpdate(nextProps,nextState){
console.log('01是否要更新数据')
console.log(nextProps) //父组件传给子组件的值,这里没有会显示空
console.log(nextState) //数据更新后的值
return true; //返回true,确认更新
}
//将要更新数据的时候触发的
componentWillUpdate(){
console.log('02组件将要更新')
}
//更新数据时候触发的生命周期函数
componentDidUpdate(){
console.log('04组件更新完成')
}
//更新数据
setMsg(){
this.setState({
msg:'我是改变后的msg数据'
})
}
render(){
console.log('03数据渲染render')
return(
<div>
{this.state.msg}
<br/>
<hr/>
<button onClick={()=>this.setMsg()}>更新msg的数据</button>
</div>
)
}
}
export default Dyw
三、卸载
当组件从 DOM 中移除时会调用如下方法:
- componentWillUnmount(): 在组件卸载及销毁之前直接调用。
import React, { Component } from 'react';
import Dyw from './components/Dyw'
class dyw extends Component {
constructor(props){
super(props)
this.state={
flag:true,
title:"我是app组件的标题"
}
}
//创建/销毁组件
setFlag(){
this.setState({
flag:!this.state.flag
})
}
//改变title
setTitle(){
this.setState({
title:'我是app组件改变后的title'
})
}
render() {
return (
<div className="App">
{
this.state.flag?<Smzq title={this.state.title}/>:''
}
<button onClick={()=>this.setFlag()}>挂载/销毁生命周期函数组件</button>
<button onClick={()=>this.setTitle()}>改变app组件的title</button>
</div>
);
}
}
export default dyw;