React生命周期

1,987 阅读3分钟

生命周期简介

React组件的生命周期实际是提供给React用于将React元素构建渲染挂载到真实的Dom节点的各个时期的钩子函数。各个生命周期函数提供,使得在开发组件时可以控制各个时期执行不同的操作,如异步的获取数据等。

react生命周期

上图是基于React: '^16.4'的生命周期

挂载

组件首次被实例化创建并插入DOM中需要执行的生命周期函数:

  • constructor():需要在组件内初始化state或进行方法绑定时,需要定义constructor()函数。不可在constructor()函数中调用setState()
  • static getDerivedStateFromProps():执行getDerivedStateFromProps函数返回我们要的更新的stateReact会根据函数的返回值拿到新的属性。
  • render():函数类组件必须定义的render()函数,是类组件中唯一必须实现的方法。render()函数应为纯函数,也就是说只要组件stateprops没有变化,返回的结果是相同的。其返回结果可以是:1、React元素;2、数组或 fragments;3、Portals;4、字符串或数值类型;5、布尔值或null。不可在render()函数中调用setState()
  • componentDidMount():组件被挂载插入到Dom中调用此方法,可以在此方法内执行副作用操作,如获取数据,更新state等操作。

更新

当组件的propsstate改变时会触发更新需要执行的生命周期函数:

  • 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组件,主要目标是在部分UIJavaScript错误不会导致整个应用崩溃,而可以进行错误处理,并进行优雅降级,渲染备用的UI。但是错误边界有一定的局限性。 错误边界无法捕获以下场景中产生的错误:

  • 事件处理
  • 异步代码(例如setTimeoutrequestAnimationFrame回调函数)
  • 服务端渲染
  • 组件自身抛出来的错误而非其子组件 分别的作用:
  • 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;
	}
}