React系列:React的生命周期

React声明周期

React组件的生命周期可以分为挂载,渲染,卸载几个阶段。

  1. 组件挂载时:
class App extends Component {
	static propTypes = {
		// ...
	};
	static defaultProps = {
		// ...
	};
	constructor(props) {
		super(props);
		this.state = {
			// ...
		};
	}
	componentWillMount() {
		// ...
	}
	componentDidMount() {
		// ...
	}
	render() {
		return <div>This is a demo.</div>;
	}
}

propTypes和defaultProps分别代表props的类型检查和默认类型。这两个属性被声明成静态属性,意味着从类外面也可以访问他们。 例如App.propTypes, App.defaultProps

  • 声明周期componentWillMount会在render之前执行,componentDidMountrender之后执行。
  • componentWillMount componentDidMount都只在组件初始化时运行一次。
  1. 组件卸载时
  • 组件卸载时只有componentWillUnMount这一个状态,在这里执行一些清理方法,例如事件回收或者清除定时器
  1. 数据更新过程
class App extends Component {
	//组件由父组件更新props而更新的话,会执行这个方法,可以作为React在pros传入后,渲染之前setState的机会,此时调用setState不会二次渲染
	componentWillReceiveProps(nextProps) {
		// this.setState({})
	}
	shouldComponentUpdate(nextProps, nextState) {
	//接收需要更新的props和state,如果返回false,组件将不再向下执行声明周期方法
		// return true;
	}
	componentWillUpdate(nextProps, nextState) {
		// ... 提供需要更新的props和state
	}
	componentDidUpdate(prevProps, prevState) {
		// ... 提供更新前的props和state
	}
	render() {
		return <div>This is a demo.</div>;
	}
}

注意: 不要在componentWillUpdate中执行setState,
在这里插入图片描述

React声明周期在不同状态下的执行顺序如下:

首次挂载组件:
按顺序执行 getDefaultProps, getInitialState, componentWillMount, render, componentDidMount

卸载组件时:
执行componentWillUnMount

重新挂载组件时:

按顺序执行 getInitialState, componentWillMount, render, componentDidMount

再次渲染组件时,组件接受到更新状态
按顺序执行componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate

注意: 使用ES6 classes来创建React组件时,static defaultProps = {} 就是调用内部的getDefaultProps方法,constructor中的this.state= {} 就是调用getInitialState方法。

图解React声明周期执行顺序

在这里插入图片描述

发布了66 篇原创文章 · 获赞 13 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/haoyanyu_/article/details/101345986