React中组件有生命周期,我们会将组件的生命周期分为四个阶段,初始化、运行中、销毁、错误处理(16.3之后)
生命周期钩子函数不能写成箭头函数。
生命周期四个阶段
初始化
在组件初始化阶段会执行
- constructor
- static getDerivedStateFromProps()
- componentWillMount() / UNSAFE_componentWillMount()
- render()
- componentDidMount()
运行
props
或state
的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:
- componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
- static getDerivedStateFromProps()
- shouldComponentUpdate() // react性能优化第二方案
- componentWillUpdate() / UNSAFE_componentWillUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
销毁
- componentWillUnmount()
错误处理
- componentDidCatch()
生命周期图
各生命周期详解
constructor
- 通过super来继承父类身上传递过来的值,让子类通过this.props接收值。
- 用来初始化一个状态。
- 初始化绑定一个方法,将this传递给这个方法。this.change = this . change.bind(this) 注意:change是个方法名字 。
- constructor 钩子函数中不能使用带副作用的代码。
componentWillMount()
- 提供一次数据修改机会
- 数据请求 fetch axios
render()
- 计算this.prop this.state*
- 返回一种类型*
1. React元素。通过jsx创建,既可以是dom元素,也可以是用户自定义的组件。
2. 字符串或数字。他们将会以文本节点形式渲染到dom中。
3. Portals【'portl】。react 16版本中提出的新的解决方案,可以使组件脱离父组件层级直接挂载在DOM树的任何位置。
4. null,什么也不渲染
5. 布尔值。也是什么都不渲染。
- render()方法必须是一个纯函数,他不应该改变state,也不能直接和浏览器进行交互,应该将事件放在其他生命周期函数中。*
4. 如果shouldComponentUpdate()返回false,render()不会被调用。*
5. jsx->vdom 对象*
componentDidMount()
组件挂载结束
1. 数据请求
2. 数据修改
3. 将render函数生成的vdom对象渲染成真实dom,然后挂载在 id 为 root 的容器中
componentWillReceiveProps()
触发: 属性发生改变,就会触发
这个钩子函数一定能监听到整个当前组件的属性变化 — > 当前组件的路由我们也可以监听到
shouldComponentUpdate()
决定组件是否更新
返回值true,更新
返回值false,不更新
默认值是true
这个钩子是React性能优化的关键钩子
componentWillUpdate()
组件即将更新,生成新的DOM。
componentDidUpdate()
组件更新结束。
1.数据更新
2.DOM操作
3.接收getSnapshotBeforeUpdate() 第三方参数作为返回值
componentWillUnmount()
销毁