React 生命周期的过程。

image.png
生命周期分为三个阶段,分别是:Mounting(挂载阶段)、Updating(更新阶段)、Unmounting(卸载阶段)。
一、挂载阶段
在挂载阶段中,首先会对组件进行挂载,执行
constructor方法创建组件,然后执行render方法告诉 React 我们的组件中会渲染什么内容,之后 React 就会开始将我们要挂载的组件挂载到 DOM 树上面,挂载完毕后 React 会回调一个生命周期函数componentDidMount,表示已经挂载成功。
class App extends Component {
constructor() {
super();
console.log('执行 constructor 方法,', 1);
}
render() {
console.log('执行 render 方法,', 2);
return (
<div>
<h2>Hello React</h2>
</div>
)
}
componentDidMount() {
console.log('执行 componentDidMount 方法,', 3);
}
}

image.png
二、更新阶段
在更新阶段中,如果我们在页面上进行数据更新修改,调用
New props、setState()、forceUpdate()后,React 就会重新调用render方法,生成一个新的 DOM 树;之后 React 会重新更新这个 DOM 树,更新完 DOM 树后会回调一个生命周期函数componentDidUpdate,表示已经更新成功。
class App extends Component {
constructor() {
super();
this.state = {
num: 0
}
}
render() {
console.log('执行 render 方法,', 1);
return (
<div>
<h2>计数:{this.state.num}</h2>
<button onClick={e => this.add()}>+1</button>
</div>
)
}
add() {
this.setState({
num: this.state.num + 1
})
}
componentDidUpdate() {
console.log('执行 componentDidMount 方法,', 2);
}
}

image.png
三、卸载阶段
在卸载阶段中,当我们的某个组件从 DOM 树中移除的时候,即将移除时会调用
componentWillUnmount函数。
class Cpn extends Component {
render() {
return (
<div>
我是 Cpn 组件
</div>
);
}
componentWillUnmount() {
console.log('执行 componentWillUnmount 方法');
}
}
class App extends Component {
constructor() {
super();
this.state = {
isShow: true
}
}
render() {
return (
<div>
<button onClick={e => this.changeShow()}>切换</button>
{this.state.isShow && <Cpn />}
</div>
)
}
changeShow() {
this.setState({
isShow: !this.state.isShow
})
}
}

image.png
四、方法
-
constructor:如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
通过this.state赋值对象来初始化内部的 state;
为事件绑定实例 (this); -
componentDidMount:会在组件挂载后(插入DOM 树中)立即调用。
依赖于 DOM 的操作可以在这里进行;
在此处发送网络请求(官方建议);
可以在此处添加定义(会在 componentWillUnmount() 取消订阅); -
componentDidUpdate:会在更新后被立即调用,首次渲染不会执行。
当组件更新后,可以在此对 DOM 进行操作;
可以对更新前后的 props 进行网络请求,当 props 未发生变化时,则不会执行网络请求; -
componentWillUnmount:会在组件卸载及销毁之前调用。
在此方法中执行必要的清理操作;
比如清除 timer ,取消网络请求或清除在 componentDidMount() 中创建的订阅等;
五、不常用的生命周期

image.png
- getDerivedStateFromProps:state 的值在任何时候都依赖于 props 时使用;该方法返回一个对象来更新 state。
- getSnapshotBeforeUpdate:在 React 更新 DOM 之前回调的一个函数,可以获取 DOM 更新前的一些信息。例如:滚动位置。
- shouldComponentUpdate(nextProps,nextState):决定是否要重新 render 组件。