一、组件的生命周期可分成三个状态(按顺序如下):
1、 挂载(Mounting):已插入真实 DOM
- constructor(): 在 React 组件挂载之前,会调用它的构造函数。
(1)如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
(2) 应在其他语句之前调用 super(props)。否则,this.props 在构造函数中可能会出现未定义的 bug。
(3) 在 constructor() 函数中不要调用 setState() 方法。如果你的组件需要使用内部 state,请直接在构造函数中为 this.state 赋值初始 state:
constructor(props) {
super(props);
this.state = {
msg: 'Hello Wrold!',
fromChildrn: '',
};
this.changeMsg = this.changeMsg.bind(this);
}
-
getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。
-
render(): render() 方法是 class 组件中唯一必须实现的方法。
render() {
return (
<>
<div className="box-body">
// 省略代码...
</div>
</>
);
}
- componentDidMount(): 在组件挂载后(插入 DOM 树中)立即调用。
(1)依赖于 DOM 节点的初始化应该放在这里。如需通过网络请求获取数据,此处是实例化请求的好地方。
2、 更新(Updating):正在被重新渲染
- getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。
- shouldComponentUpdate():当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。
- render(): render() 方法是 class 组件中唯一必须实现的方法。
- getSnapshotBeforeUpdate(): 在最近一次渲染输出(提交到 DOM 节点)之前调用。
- componentDidUpdate(): 在更新后会被立即调用。
首次渲染不会执行此方法。
3、 卸载(Unmounting):已移出真实 DOM
- componentWillUnmount(): 在组件卸载及销毁之前直接调用。
二、注意:
(1) render() 方法是 class 组件中唯一必须实现的方法,其他方法可以根据自己的需要来实现。
(2) componentDidMount() 如果添加了订阅,请不要忘记在 componentWillUnmount() 里取消订阅
详细可参考官网
三、实例
Clock.jsx
import React from 'react';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
};
}
componentDidMount() {
console.log('挂载完成' + this.state.date.toLocaleTimeString());
this.tiemTick = setInterval(() => {
this.tick();
}, 1000);
}
componentDidUpdate() {
console.log('更新了');
}
componentWillUnmount() {
console.log('销毁前');
clearInterval(this.tiemTick);
}
tick() {
this.setState({ date: new Date() });
}
render() {
return <div>{this.state.date.toLocaleTimeString()}</div>;
}
}
export default Clock;
index.jsx
import Clock from './components/Clock';
export default () => {
return <Clock />;
};