文章目录
1. 生命周期(旧 16)
1.1 生命周期对应状态
-
constructor
// 第一次初始化,类组件实例化调用构造器
-
componentWillMount
// 组件将要挂载
-
render
// 组件渲染到页面
-
componentDidMount
// 组件挂载完成
-
componentWillUnmount
// 组件将要卸载
-
componentWillReceiveProps
// 父组件传入的 props 值更新时,子组件的该钩子触发
-
shouldComponentUpdate
// 数据发生改变是否允许组件(视图)进行更新,该函数通过返回 true(默认值)、false 进行判断,这个时候数据已经更新了
-
componentWillUpdate
// 组件将要更新
-
componentDidUpdate
// 组件更新完成
1.2 单个组件的流程
1.2.1 初始化流程
由 ReactDOM.render() 触发
- constructor
- componentWillMount
- render
- componentDidMount
- 4
1.2.2更新数据
- 由 this.setState() 触发
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
- 4
- 由 this.forceUpdate() 触发(强制组件更新)
- componentWillUpdate
- render
- componentDidUpdate
- 3
1.2.3 卸载流程
由 ReactDOM.unmountComponentAtNode() 触发
- componentWillUnmount
- 1
1.3 嵌套组件的流程
1.3.1 初始化流程
由 ReactDOM.render() 触发
- 父亲 constructor
- 父亲 componentWillMount
- 父亲 render
- 孩子 constructor
- 孩子 componentWillMount
- 孩子 render
- 孩子 componentDidMount
- 父亲 componentDidMount
- 3 - 4 - 1
1.3.2 更新数据
- 由 this.setState() 触发
- 父亲 shouldComponentUpdate
- 父亲 componentWillUpdate
- 父亲 render
- 孩子 componentWillReceiveProps
- 孩子 shouldComponentUpdate
- 孩子 componentWillUpdate
- 孩子 render
- 孩子 componentDidUpdate
- 父亲 componentDidUpdate
- 3 - 5 - 1
- 由 this.forceUpdate() 触发(强制组件更新)
- 父亲 componentWillUpdate
- 父亲 render
- 孩子 componentWillReceiveProps
- 孩子 shouldComponentUpdate
- 孩子 componentWillUpdate
- 孩子 render
- 孩子 componentDidUpdate
- 父亲 componentDidUpdate
- 2 - 5 - 1
1.3.3 卸载流程
由 ReactDOM.unmountComponentAtNode() 触发
- 父亲 componentWillUnmount
- 孩子 componentWillUnmount
- 1 - 1
2. 生命周期(新 17)
2.1 不建议使用的三个钩子函数
- 在新版本中,不建议使用旧版本的个别生命周期
- 新版本中,即将废弃三个 Will 除了组件销毁那个,componentWillMount、componentWillReceiveProps、componentWillUpdate
- 但是如果非要使用的话,前面要加上 UNSAFE_
2.2 新的钩子函数
-
getDerivedStateFromProps
-
在初始化时,constructor → getDerivedStateFromProps → render
-
在更新时,getDerivedStateFromProps → shouldComponentUpdate
-
当然之前的生命周期也还在
// 必须要有返回值 // null:并没有影响 // object:会修改 state 中的值 // 如果返回的是 state 本身,没有影响 // 如果返回的是 props 或自定义对象,那么页面上的数据将不在作为响应式了 class Demo extends React.Component { static getDerivedStateFromProps(props, state){ return Null/Object } }
-
-
getSnapshotBeforeUpdate
-
只会在更新时调用
-
render → getSnapshotBeforeUpdate → componentDidUpdate
// getSnapshotBeforeUpdate 可以获取更新之前的 props 和 state // 必须要有返回值,并且会把返回值传给 componentDidUpdate class Demo extends React.Component { getSnapshotBeforeUpdate(preProps, preState) { return "我要传给更新完成的数据"; }; componentDidUpdate(preProps, preState, snapshotValue){ // snapshotValue 传过来的数据 }; }
-
-
这两个钩子并不常用,但是需要的时候也是会用到的
-
常用的有 render、componentDidMount、componentWillUnmount