React生命周期

生命周期简介

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

react生命周期

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

挂载

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

  • constructor():须要在组件内初始化state或进行方法绑定时,须要定义constructor()函数。不可在constructor()函数中调用setState()
  • static getDerivedStateFromProps():执行getDerivedStateFromProps函数返回咱们要的更新的stateReact会根据函数的返回值拿到新的属性。
  • render():函数类组件必须定义的render()函数,是类组件中惟一必须实现的方法。render()函数应为纯函数,也就是说只要组件stateprops没有变化,返回的结果是相同的。其返回结果能够是:一、React元素;二、数组或 fragments;三、Portals;四、字符串或数值类型;五、布尔值或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;
	}
}
复制代码
相关文章
相关标签/搜索