React 组件的生命周期分为三部分:
- 组件的挂载阶段
- 组件的更新阶段
- 组件的卸载阶段
注意:
组件只有在定义为 类 的前提下才会拥有的生命周期等钩子函数,因为函数式组件是没有实例的
要定义React组件类,需要继承React.Component:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
生命周期图
Mounting 挂载阶段
组件的挂载阶段可以理解为组件的创建阶段,组件实例被创建并将其插入虚拟DOM中时,将执行以下钩子函数:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
注意:
以下方法会有安全性问题,在 React 的 17.X版本中将移除,在新的代码中应避免:
componentWillMount()
Updating 更新阶段
组件的更新阶段, 新的props、setState()、foreceUpdate() 都会去执行以下阶段的钩子函数:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
注意:
以下方法会有安全性问题,在 React 的 17.X版本中将移除,在新的代码中应避免:
componentWillUpdatet()componentWillReceiveProps()
Unmounting 卸载阶段
- componentWillUnmount()