【09】基础知识:React组件的生命周期

组件从创建到死亡它会经历一些特定的阶段。

React 组件中包含一系列勾子函数(生命周期回调函数 <=> 生命周期钩子函数 <=> 生命周期函数 <=> 生命周期钩子),会在特定的时刻调用。

我们在定义组件时,会在特定的生命周期回调函数中,做特定的工作。

一、react 生命周期旧

在这里插入图片描述

初始化阶段:由 ReactDOM.render() 触发,初次渲染

1、构造器:constructor()

2、组件将要挂载的钩子:componentWillMount()

3、组件渲染或组件更新的钩子:render()

4、 组件挂载完毕的钩子:componentDidMount()

更新阶段:由组件内部 this.setSate() / this.forceUpdate() 或父组件 render 触发

1、控制组件更新的 “阀门” :shouldComponentUpdate()

2、组件将要更新的钩子:componentWillUpdate()

3、组件渲染或组件更新的钩子:render()

4、组件更新完毕的钩子:componentDidUpdate()

卸载组件:由 ReactDOM.unmountComponentAtNode() 触发

1、组件将要卸载的钩子:componentWillUnmount()

父组件 render:组件 props 值改变触发

1、组件将要接收新的 props 的钩子:componentWillReceiveProps()

二、react 生命周期新

在这里插入图片描述
初始化阶段:由 ReactDOM.render() 触发,初次渲染

1、构造器:constructor()

2、从 props 得到一个派生状态:static getDerivedStateFromProps()

3、组件渲染或组件更新的钩子:render()

4、 组件挂载完毕的钩子:componentDidMount()

更新阶段:由组件内部 this.setSate() / this.forceUpdate() 或父组件 render 触发

1、static getDerivedStateFromProps()

2、控制组件更新的 “阀门” :shouldComponentUpdate()

3、组件渲染或组件更新的钩子:render()

4、在更新之前获取快照:getSnapshotBeforeUpdate()

5、组件更新完毕的钩子:componentDidUpdate()

卸载组件:由 ReactDOM.unmountComponentAtNode() 触发

1、组件将要卸载的钩子:componentWillUnmount()

三、新旧生命周期总结

重要的勾子

1、组件渲染或组件更新的钩子:render()

2、组件挂载完毕的钩子:componentDidMount()

一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息

3、组件将要卸载的钩子:componentWillUnmount()

一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息

即将废弃的勾子

现在使用会出现警告,下一个大版本需要加上 UNSAFE_ 前缀才能使用,以后可能会被彻底废弃,不建议使用。

1、组件将要挂载的钩子:componentWillMount()

2、组件将要接收新的 props 的钩子:componentWillReceiveProps()

3、组件将要更新的钩子:componentWillUpdate()

四、案例

案例1:引出生命周期

需求:定义组件实现以下功能:

1、让指定的文本做显示 / 隐藏的渐变动画

2、从完全可见,到彻底消失,耗时 2S

3、点击 “不活了” 按钮从界面中卸载组件

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>1_引出生命周期</title>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>

	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<script type="text/babel">
		// 创建组件
		class Life extends React.Component {
      
      
			state = {
      
       opacity: 1 }

			death = () => {
      
      
				// clearInterval(this.timer) // 清除定时器(可以卸载componentWillUnmount中)
				ReactDOM.unmountComponentAtNode(document.getElementById('test')) // 卸载组件
			}

			// 组件挂载完毕的钩子
			componentDidMount() {
      
      
				console.log('componentDidMount')
				this.timer = setInterval(() => {
      
      
					let {
      
       opacity } = this.state // 获取原状态
					opacity -= 0.1 // 减小0.1
					if (opacity <= 0) opacity = 1 
					this.setState({
      
       opacity }) // 设置新的透明度
				}, 200)
			}

			// 组件将要卸载的钩子
			componentWillUnmount() {
      
      
				console.log('componentWillUnmount')
				clearInterval(this.timer) // 清除定时器
			}
			
			// 初始化渲染、状态更新之后 (state变化会触发render函数,定时器如果写在render中,会造成无限递归)
			render() {
      
      
				console.log('render')
				return (
					<div>
						<h2 style={
      
      {
      
       opacity: this.state.opacity }}>React学不会怎么办?</h2>
						<button onClick={
      
      this.death}>不活了</button>
					</div>
				)
			}
		}

		// 渲染组件
		ReactDOM.render(<Life />, document.getElementById('test'))
	</script>
</body>
</html>

案例二:React 生命周期旧

累加器,点击数值+1

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>2_react生命周期(旧)</title>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>

	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<script type="text/babel">
		//  创建组件
		class Count extends React.Component {
      
      
			// 构造器
			constructor(props) {
      
      
				console.log('Count---constructor')
				super(props)
				this.state = {
      
       count: 0 } // 初始化状态
			}

			// 加1按钮的回调
			add = () => {
      
      
				const {
      
       count } = this.state
				this.setState({
      
       count: count+1 }) // 更新状态
			}

			// 卸载组件按钮的回调
			death = () => {
      
      
				ReactDOM.unmountComponentAtNode(document.getElementById('test'))
			}

			// 强制更新按钮的回调
			force = () => {
      
      
				this.forceUpdate()
			}

			// 组件将要挂载的钩子
			componentWillMount() {
      
      
				console.log('Count---componentWillMount')
			}

			// 控制组件更新的 “阀门” 
			shouldComponentUpdate() {
      
      
				console.log('Count---shouldComponentUpdate')
				// 不写时,默认值为true,代表允许组件更新;写了以后,必须有返回值Boolan,true/false
				return true
			}

			// 组件将要更新的钩子
			componentWillUpdate() {
      
      
				console.log('Count---componentWillUpdate')
			}

			// 组件渲染或组件更新的钩子
			render() {
      
      
				console.log('Count---render')
				const {
      
       count } = this.state
				return (
					<div>
						<h2>当前求和为:{
      
       count }</h2>
						<button onClick={
      
      this.add}>点我+1</button>
						<button onClick={
      
      this.death}>卸载组件</button>
						<button onClick={
      
      this.force}>不更改任何状态中的数据,强制更新一下</button>
					</div>
				)
			}

			// 组件挂载完毕的钩子
			componentDidMount() {
      
      
				console.log('Count---componentDidMount')
			}

			// 组件更新完毕的钩子
			componentDidUpdate() {
      
      
				console.log('Count---componentDidUpdate')
			}

			// 组件将要卸载的钩子
			componentWillUnmount() {
      
      
				console.log('Count---componentWillUnmount')
			}
		}

		// 渲染组件
		ReactDOM.render(<Count />, document.getElementById('test'))
	</script>
</body>
</html>

父组件 render 触发子组件 props 值改变

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>2_react生命周期(旧)</title>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="car"></div>

	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<script type="text/babel">
		// 父组件
		class A extends React.Component {
      
      
			// 初始化状态
			state = {
      
       carName: '奔驰' }

			changeCar = () => {
      
      
				this.setState({
      
       carName: '奥拓' })
			}

			render() {
      
      
				return (
					<div>
						<div>我是A组件</div>
						<button onClick={
      
      this.changeCar}>换车</button>
						<B carName={
      
      this.state.carName}/>
					</div>
				)
			}
		}

		// 子组件
		class B extends React.Component {
      
      
			// 组件将要接收新的props的钩子(props第一次接收值时不触发)
			componentWillReceiveProps(props) {
      
      
				console.log('B---componentWillReceiveProps', props)
			}

			// 控制组件更新的 “阀门” 
			shouldComponentUpdate() {
      
      
				console.log('B---shouldComponentUpdate')
				// 不写时,默认值为true,代表允许组件更新;写了以后,必须有返回值Boolan,true/false
				return true
			}

			// 组件将要更新的钩子
			componentWillUpdate() {
      
      
				console.log('B---componentWillUpdate')
			}

			// 组件渲染或组件更新的钩子
			render() {
      
      
				console.log('B---render')
				const {
      
       carName } = this.props
				return (
					<div>我是B组件,接收到的车是:{
      
      carName}</div>
				)
			}

			// 组件更新完毕的钩子
			componentDidUpdate() {
      
      
				console.log('Count---componentDidUpdate')
			}
		}

		// 渲染组件
		ReactDOM.render(<A />, document.getElementById('car'))
	</script>
</body>
</html>

案例三:React 生命周期新

新生命周期新增方法:

static getDerivedStateFromProps() 从props得到一个派生状态,此方法适用于罕见的用例,即 state 的值在任何时候都取决于 props 。派生状态会导致代码冗余。

getSnapshotBeforeUpdate() 在更新之前获取快照,此用法并不常见。它使得组件能在发生改变之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>3_react生命周期(新)</title>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>

	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

	<script type="text/babel">
		// 创建组件
		class Count extends React.Component {
      
      
			// 构造器
			constructor(props) {
      
      
				console.log('Count---constructor')
				super(props)
				this.state = {
      
       count: 0 } // 初始化状态
			}

			// 加1按钮的回调
			add = () => {
      
      
				const {
      
       count } = this.state
				this.setState({
      
       count: count+1 }) // 更新状态
			}

			// 卸载组件按钮的回调
			death = () => {
      
      
				ReactDOM.unmountComponentAtNode(document.getElementById('test'))
			}

			// 强制更新按钮的回调
			force = () => {
      
      
				this.forceUpdate()
			}

			// 从props得到一个派生状态:若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps
			static getDerivedStateFromProps(props, state) {
      
      
				console.log('getDerivedStateFromProps', props, state)
				return null // 必须有返回值,状态对象或者null
			}

			// 在更新之前获取快照
			getSnapshotBeforeUpdate() {
      
      
				console.log('getSnapshotBeforeUpdate')
				return 'atguigu' // 必有有返回值,快照或者null,将作为参数传递给 componentDidUpdate()
			}

			// 控制组件更新的 “阀门” 
			shouldComponentUpdate() {
      
      
				console.log('Count---shouldComponentUpdate')
				// 不写时,默认值为true,代表允许组件更新;写了以后,必须有返回值Boolan,true/false
				return true
			}

			// 组件渲染或组件更新的钩子
			render() {
      
      
				console.log('Count---render')
				const {
      
       count } = this.state
				return (
					<div>
						<h2>当前求和为:{
      
       count }</h2>
						<button onClick={
      
      this.add}>点我+1</button>
						<button onClick={
      
      this.death}>卸载组件</button>
						<button onClick={
      
      this.force}>不更改任何状态中的数据,强制更新一下</button>
					</div>
				)
			}

			// 组件挂载完毕的钩子
			componentDidMount() {
      
      
				console.log('Count---componentDidMount')
			}

			// 组件更新完毕的钩子(接收参数:之前的的props、之前的state、传过来的快照)
			componentDidUpdate(prevProps, prevState, snapshotValue) {
      
      
				console.log('Count---componentDidUpdate', prevProps, prevState, snapshotValue)
			}

			// 组件将要卸载的钩子
			componentWillUnmount() {
      
      
				console.log('Count---componentWillUnmount')
			}

		}

		//渲染组件
		ReactDOM.render(<Count count={
      
       199 } />, document.getElementById('test'))
	</script>
</body>
</html>

案例四:getSnapShotBeforeUpdate 的使用场景

展示新闻列表,1s向上追加一条新闻,并保证页面视图区域内容不变。

思路:

利用 getSnapShotBeforeUpdate() 获取组件更新之前 内容的 scrollHeight,传递给 componentDidUpdate()

组件更新之后,设置当前容器的 scrollTop 值为,当前内容高度 - 组件更新之前内容高度

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>4_getSnapShotBeforeUpdate的使用场景</title>
	<style>
		.list {
      
      
			width: 200px;
			height: 150px;
			background-color: skyblue;
			overflow: auto;
		}

		.news {
      
      
			height: 30px;
		}
	</style>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>

	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

	<script type="text/babel">
		class NewsList extends React.Component {
      
      
			state = {
      
       newsArr: [] }

			componentDidMount() {
      
      
				setInterval(() => {
      
      
					const {
      
       newsArr } = this.state // 获取原状态
					const news = '新闻' + (newsArr.length + 1) // 模拟一条新闻
					this.setState({
      
       newsArr: [news, ...newsArr] }) // 更新状态
				}, 1000)
			}

			getSnapshotBeforeUpdate() {
      
      
				return this.refs.list.scrollHeight
			}

			componentDidUpdate(preProps, preState, height) {
      
      
				this.refs.list.scrollTop += this.refs.list.scrollHeight - height
			}

			render() {
      
      
				return (
					<div className="list" ref="list">
						{
      
      
							this.state.newsArr.map((n, index) => {
      
      
								return <div key={
      
      index} className="news">{
      
      n}</div>
							})
						}
					</div>
				)
			}

		}

		ReactDOM.render(<NewsList />, document.getElementById('test'))
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_45559449/article/details/133827646