1、介绍
组件生命周期:指的是组件从开始到结束的过程,中间会经历一些特定的时刻,如创建、实例化、渲染组件到页面(挂载)、state状态变化、组件从页面移除(卸载)等等。
钩子函数:组件经历到生命周期某些特定时刻时,某个特定的函数会被自动调用,这些特定的函数就称为钩子函数(生命周期回调函数),React组件中包含一系列勾子函数。
钩子函数作用:开发者在定义组件时,可以在组件生命周期某时刻对应的钩子函数中实现指定的功能,例如组件被渲染到页面,然后立刻发起HTTP请求服务端数据。
2、组件生命周期详解
旧版本React生命周期(17版本以前)
上图所示,React组件生命周期大概分为三个阶段
一、初始化阶段:由ReactDOM.render()触发,下列函数会被依次调用
①constructor(); 通过new关键字创建组件实例对象。
②componentWillMount(); 组件被挂载到页面前。
③render(); 组件被挂载到页面。
④componentDidMount(); 组件被挂载到页面后。
二、更新阶段:由组件内部state改变或父组件重新render触发,下列函数会被依次调用
①shouldComponentUpdate(); 控制组件是否应该被更新,返回true时,后续三个函数继续执行,返回false则不执行。
②componentWillUpdate(); 组件被更新之前。
③render(); 组件更新,重新渲染到页面。
④componentDidUpdate(); 组件被更新之后。
三、卸载组件:由ReactDOM.unmountComponentAtNode()触发,仅一个函数会被调用
①componentWillUnmount(); 组件被卸载前被调用。
使用较为频繁的钩子函数总结:
- componentDidMount():组件挂载完成后做的一些初始化操作,如发起HTTP请求、订阅消息等。
- componentWillUnmount():组件卸载前的一些收尾操作,如清理未关闭的定时器、取消订阅消息等。
- render():类组件必用的钩子函数。
新版本React生命周期(17版本及以后)
待续。。。
3、演示钩子函数使用
旧版本React生命周期钩子函数(实际17、18版本也能使用)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件生命周期</title>
</head>
<body>
<div id="container"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
<script type="text/babel" >
class Person extends React.Component{
//构造器,类组件被实例化的时候首先被调用
constructor(props){
super(props)
console.log("constructor execute");
}
//初始化state状态属性
state = {"count":1};
//组件被挂载,组件更新时都会被调用
render(){
console.log("render execute");
return (
<div>
当前组件状态:{this.state.count}<br/><br/>
<button onClick={this.changeState}>点击更新组件状态</button><br/><br/>
<button onClick={this.removeComponent}>点击卸载组件</button>
</div>
);
}
changeState = ()=>{
const {count} = this.state;
this.setState({"count":count+1})
}
removeComponent = ()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('container'))
}
//组件将要挂载的钩子
componentWillMount(){
console.log("componentWillMount execute");
}
//组件挂载完毕的钩子
componentDidMount(){
console.log('componentDidMount execute');
}
//组件将要卸载的钩子
componentWillUnmount(){
console.log('componentWillUnmount execute');
}
//控制组件是否应该被更新(返回true组件将会被更新,返回flase组件不会被更新)
shouldComponentUpdate(){
console.log('shouldComponentUpdate execute');
return true
}
//组件将要更新的钩子
componentWillUpdate(){
console.log('componentWillUpdate execute');
}
//组件更新完毕的钩子
componentDidUpdate(){
console.log('componentDidUpdate execute');
}
}
ReactDOM.render(<Person/>,document.getElementById('container'))
</script>
</body>
</html>