React
组件的生命周期实际是提供给React
用于将React
元素构建渲染挂载到真实的Dom
节点的各个时期的钩子函数。各个生命周期函数提供,使得在开发组件时能够控制各个时期执行不一样的操做,如异步的获取数据等。 javascript
上图是基于
React: '^16.4'
的生命周期java
组件首次被实例化建立并插入DOM
中须要执行的生命周期函数:react
state
或进行方法绑定时,须要定义constructor()
函数。不可在constructor()
函数中调用setState()
。getDerivedStateFromProps
函数返回咱们要的更新的state
,React
会根据函数的返回值拿到新的属性。render()
函数,是类组件中惟一必须实现的方法。render()
函数应为纯函数,也就是说只要组件state
和props
没有变化,返回的结果是相同的。其返回结果能够是:一、React
元素;二、数组或 fragments;三、Portals;四、字符串或数值类型;五、布尔值或null。不可在render()
函数中调用setState()
。Dom
中调用此方法,能够在此方法内执行反作用操做,如获取数据,更新state
等操做。当组件的props
或state
改变时会触发更新须要执行的生命周期函数:数组
getDerivedStateFromProps
会在调用 render
方法以前调用,而且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新state
,若是返回null
则不更新任何内容。shouldComponentUpdate()
的返回值,判断React
组件的是否执行更新操做。React.PureComponent
就是基于浅比较进行性能优化的。通常在实际组件实践中,不建议使用该方法阻断更新过程,若是有须要建议使用React.PureComponent
。shouldComponentUpdate()
返回false
值时,将不执行render()
函数。pre-commit
阶段,此时已经能够拿到Dom
节点数据了,该声明周期返回的数据将做为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;
}
}
复制代码