React的生命周期
React 组件的生命周期的三个状态:
- Mounting : 挂载过程
- Updating : 更新过程
- Unmounting : 卸载过程
React 旧版

挂载 Mount
当组件实例被创建并插入 DOM 中时。
- constructor : 初始化 state,为事件处理函数绑定实例。
- componentWillMount : 在挂载之前被调用
- render
- componentDidMount : 会在组件挂载后立即调用。依赖于 DOM 节点的初始化、请求数据、添加订阅应该放在这里。
更新 Update
当组件的 props 或 state 发生变化时会触发更新。
- componentWillReceiveProps : 接收到一个新的 props 时被调用触发,初始渲染不会调用此方法。
- shouldComponentUpdate : 根据 shouldComponentUpdate() 的返回的 bool 值来决定是否重新渲染组件.
- componentWillUpdate : 当组件收到新的 props 或 state 时,会在渲染之前调用 初始渲染不会调用此方法。
- render
- componentDidUpdate : 会在更新后会被立即调用。首次渲染不会执行此方法。
卸载 Unmount
当组件从 DOM 中移除时会调用如下方法
- componentWillUnmount : 会在组件卸载及销毁之前直接调用。
示例代码
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 | |
16 | |
17 | |
18 | |
19 | |
20 | |
21 | |
22 | |
23 | |
24 | |
25 | |
26 | |
27 | |
28 | |
29 | |
30 | |
31 | |
32 | |
33 | |
34 | |
35 | |
36 | |
37 | |
38 | |
39 | |
40 | |
41 | |
42 | |
43 | |
44 | |
45 | |
46 | |
47 | |
48 | |
49 | |
50 | |
51 | |
52 | |
53 | |
54 | |
55 | |
56 | |
57 | |
58 | |
59 | |
60 | |
61 | |
62 | |
63 | |
64 | |
65 | |
66 | |
67 | |
68 | |
69 | |
70 | |
71 | |
72 | |
73 | |
74 | |
75 | |
76 | |
77 | |
78 | |
79 | |
80 | |
81 | |
React 新版

即将废弃
- componentWillMount ——> UNSAFE_componentWillMount
- componentWillReceiveProps ——> UNSAFE_componentWillReceiveProps
- componentWillUpdate ——> UNSAFE_componentWillUpdate
新增
- static getDerivedStateFromProps
- getSnapshotBeforeUpdate
组件挂载 Mount
当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
- constructor : 初始化 state,为事件处理函数绑定实例。
- static getDerivedStateFromProps : 返回一个状态对象或者null
- render
- componentDidMount : 会在组件挂载后立即调用。依赖于 DOM 节点的初始化、请求数据、添加订阅应该放在这里。
更新 Update
当组件的 props 或 state 发生变化时会触发更新。
- static getDerivedStateFromProps : 返回一个状态对象或者null
- shouldComponentUpdate : 根据 shouldComponentUpdate() 的返回的 bool 值来决定是否重新渲染组件
- render
- getSnapshotBeforeUpdate : 返回一个 snapshot 或者 null
- componentDidUpdate : 会在更新后会被立即调用。首次渲染不会执行此方法。
卸载 Unmount
当组件从 DOM 中移除时会调用如下方法
- componentWillUnmount : 会在组件卸载及销毁之前直接调用。
示例代码
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 | |
16 | |
17 | |
18 | |
19 | |
20 | |
21 | |
22 | |
23 | |
24 | |
25 | |
26 | |
27 | |
28 | |
29 | |
30 | |
31 | |
32 | |
33 | |
34 | |
35 | |
36 | |
37 | |
38 | |
39 | |
40 | |
41 | |
42 | |
43 | |
44 | |
45 | |
46 | |
47 | |
48 | |
49 | |
50 | |
51 | |
52 | |
53 | |
54 | |
55 | |
56 | |
57 | |
58 | |
59 | |
60 | |
61 | |
62 | |
63 | |
64 | |
65 | |
66 | |
67 | |
68 | |
69 | |
70 | |
71 | |
72 | |
73 | |
74 | |
75 | |
76 | |
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!