一、生命周期简介
React组件的生命周期可以分为三个阶段:挂载、更新和卸载。
挂载 (Mounting) 阶段:
constructor() 构造函数,在组件实例化时被调用。
render() 渲染组件,必须定义。
componentDidMount() 组件挂载完成后调用,常用于执行一些需要 DOM 的操作。如:开启定时器、发送网络请求、订阅消息等
更新 (Updating) 阶段:
shouldComponentUpdate() 返回布尔值,判断是否需要重新渲染组件。
render() 渲染组件,必须定义。
componentDidUpdate() 更新后调用,常用于执行一些需要 DOM 的操作。
卸载 (Unmounting) 阶段:
componentWillUnmount() 组件卸载前调用,常用于清除计时器、取消订阅等。
二、案列演示
我们定义一个类,在里面写上各个生命周期函数,渲染到页面上
class Sum extends React.Component{
//构造器
constructor(props){
console.log("Sum---constructor");
super(props)
//初始化状态
this.state={sum:0}
}
//加1按钮的回调
add=()=>{
//获取原状态
const {sum}=this.state
//更新状态
this.setState({sum:sum+1})
}
//卸载组件的回调
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//强制更新的回调
force=()=>{
//调用强制更新的函数
this.forceUpdate()
}
//组件将要挂载时的生命周期函数
componentWillMount(){
console.log("Sum---componentWillMount");
}
//组件挂载完毕的生命周期函数
componentDidMount(){
console.log("Sum---componentDidMount");
}
//组件将要卸载时的生命周期函数
componentWillUnmount(){
console.log("Sum---componentWillUnmount");
}
//控制组件更新的“阀门”
shouldComponentUpdate(){
console.log("Sum---shouldComponentUpdate");
return true;
}
//组件将要更新的生命周期函数
componentWillUpdate(){
console.log("Sum---componentWillUpdate");
}
//组件更新完毕的生命周期函数
componentDidUpdate(){
console.log("Sum---componentDidUpdate");
}
render(){
console.log("Sum---render");
const {sum}=this.state
return(
<div>
<h2>当前求和为:{sum}</h2>
<button onClick={this.add}>点击+1</button>
<button onClick={this.death}>卸载组件</button>
<button onClick={this.force}>强制更新组件</button>
</div>
)
}
}
执行代码:初始渲染的输出
清空控制台,点击+1按钮
点击强制更新按钮
注意:强制更新使用forceUpdate()方法
三、父组件Render
定义一个A组件和B组件,B组件作为A组件的子组件。A组件将值传递给B组件
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时的生命周期函数
componentWillReceiveProps(props){
console.log("B---componentWillReceiveProps",props);
}
render(){
return(
<div>
我是B组件,我接收的车是:{this.props.carName}
</div>
)
}
}
//渲染组件
ReactDOM.render(<A/>,document.getElementById('test'))
点击换一台车
注意:第一次渲染不会调用componentWillReceiveProps方法
个人博客:余生的学习笔记