生命周期简介
`React`组件的生命周期实际是提供给`React`用于将`React`元素构建渲染挂载到真实的`Dom`节点的各个时期的钩子函数。各个生命周期函数提供,使得在开发组件时可以控制各个时期执行不同的操作,如异步的获取数据等。
![dacd8d1fcca62e20eae782f5d900552d.png](https://i-blog.csdnimg.cn/blog_migrate/bb0bb860c892d28b1ae1339b5d0d20d0.jpeg)
上图是基于`React: '^16.4'`的生命周期
挂载
组件首次被实例化创建并插入`DOM`中需要执行的生命周期函数:
- constructor():需要在组件内初始化`state`或进行方法绑定时,需要定义`constructor()`函数。不可在`constructor()`函数中调用`setState()`。
- static getDerivedStateFromProps():执行`getDerivedStateFromProps`函数返回我们要的更新的`state`,`React`会根据函数的返回值拿到新的属性。
- render():函数类组件必须定义的`render()`函数,是类组件中唯一必须实现的方法。`render()`函数应为纯函数,也就是说只要组件`state`和`props`没有变化,返回的结果是相同的。其返回结果可以是:1、`React`元素;2、数组或 fragments;3、Portals;4、字符串或数值类型;5、布尔值或null。不可在`render()`函数中调用`setState()`。
- componentDidMount():组件被挂载插入到`Dom`中调用此方法,可以在此方法内执行副作用操作,如获取数据,更新`state`等操作。
更新
当组件的`props`或`state`改变时会触发更新需要执行的生命周期函数:
- static getDerivedStateFromProps():`getDerivedStateFromProps`会在调用 `render`方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新`state`,如果返回`null`则不更新任何内容。
- shouldComponentUpdate():根据`shouldComponentUpdate()`的返回值,判断`React`组件的是否执行更新操作。`React.PureComponent`就是基于浅比较进行性能优化的。一般在实际组件实践中,不建议使用该方法阻断更新过程,如果有需要建议使用`React.PureComponent`。
- render():在组件更新阶段时如果`shouldComponentUpdate()`返回`false`值时,将不执行`render()`函数。
- getSnapshotBeforeUpdate():该生命周期函数执行在`pre-commit`阶段,此时已经可以拿到`Dom`节点数据了,该声明周期返回的数据将作为`componentDidUpdate()`第三个参数进行使用。
- componentDidUpdate():`shouldComponentUpdate()`返回值`false`时,则不会调用`componentDidUpdate()`。
卸载
`componentWillUnmount()`会在组件卸载及销毁之前直接调用。一般使用此方法用于执行副作用的清理操作,如取消定时器,取消事件绑定等。
import React from 'react';
export default class CancelDocumentEffect extends React.Component {
handleDocumentClick = (e) => {
console.log(`document has clicked: ${e}`);
}
componentDidMount() {
document.addEventLister('click', this.handleDocumentClick, false);
}
componentWillUnmount() {
document.removeEventLister('click', this.handleDocumentClick, false);
}
render() {
return (<p>this is test!</p>)
}
}
错误处理
当渲染过程,生命周期,或子组件的构造函数中抛出错误会执行`static getDerivedStateFromError()`或`componentDidCatch()`生命周期函数。且基于此,`React: '^16.0.0'`提出了错误边界的概念。错误边界其实是一种能够捕获它的子组件树所产生的错误的`React`组件,主要目标是在部分`UI`的`JavaScript`错误不会导致整个应用崩溃,而可以进行错误处理,并进行优雅降级,渲染备用的`UI`。但是错误边界有一定的局限性。
错误边界无法捕获以下场景中产生的错误:
- 事件处理
- 异步代码(例如`setTimeout`或`requestAnimationFrame`回调函数)
- 服务端渲染
- 组件自身抛出来的错误而非其子组件
分别的作用:
- `static getDerivedStateFromError(error)`:在渲染阶段调用,不允许执行副作用,因此用户渲染降级备用的`UI`
- `componentDidCatch(error, errorInfo)`:在提交阶段调用,可以执行副作用。 因此可用于记录错误之类的情况
import React from 'react';
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error) {
this.setState({hasError: true});
}
componentDidCatch(error, errorInfo) {
logService(error, errorInfo);
}
render() {
const {hasError} = this.state;
const backupUI = <div>发生错误</div>
return hasError ? backupUI : this.props.children;
}
}