2022 年 7 月 6 日
四个阶段
React 组件的生命周期被分为四个阶段:
- 初始化 (initialization)
- 挂载 (mounting)
- 更新 (updating)
- 卸载 (unmounting)
在每个阶段, 不同的生命周期函数都会被相应的调用.
在初始化阶段, 通过 props 和默认的值, 我们将组件创建出来;
在挂载阶段, 调用 render 函数;
在更新阶段, 因为某个状态的改变, 组件需要被重新渲染, 因此再次调用 render 函数;
在卸载阶段, 组件会从页面中被移除。
生命周期
React 组件的生命周期如下:
+----------------+
| initialization |
+----------------+
|
|- constructor()
|
+----------------+
| mounting |
+----------------+
|
|- componentWillMount()
|
|- render()
|
|- componentDidMount()
|
+----------------+
| updating |
+----------------+
|
|- shouldComponentUpdate() -> True
|
|- componentWillUpdate()
|
|- render()
|
|- componentDidUpdate()
|
+----------------+
| unmounting |
+----------------+
|
|- componentWillUnmount()
一些细节
在更新阶段中, 两个情况会触发更新:
- 组件内部 state 更新
- 组件的 props 更新
在 React Hooks 中的生命周期函数
在 React Hooks 中, 使用 useEffect 来调用生命周期函数.
componentDidMount
useEffect(() => {
// component did mount code goes here.
}, []);
componentDidUpdate
useEffect(() => {
// component did mount code goes here.
}, [dependency]); // update if the dependency is updated.