一、常用的生命周期函数
生命周期.png
1.constructor
- 用于初始化内部状态
- 唯一可以直接修改state的地方,
this.state.num = 123
2.getDerivedStateFromProps react16中的新API - 当state需要从props初始化时使用
- 尽量不要使用:维护二者统一性会导致难度的增加
- 每次render的时候都会调用
- 应用场景: 表单控件需要一个默认值,默认值从props中获取,之后的值为用户修改的value
3.componentDidMount - ui渲染完成之后调用
- 只执行一次
- 用来发送ajax请求
4.shouldComponentUpdate - 决定虚拟DOM 是否重绘
- 应用场景: 性能优化
5.getSnapshotBeforeUpdate - 在页面render之前调用,state已更新
- 典型场景: 获取render之前的DOM状态 [ https://codesandbox.io/s/6n20nrzlxz],demo中C4为每秒动态增加信息,滑动看之前的信息,会出现滚动条抖动的情况
6.componentDidUpdate - 每次UI更新时被调用
- 典型场景:页面需要根据props变化重新获取数据
7.componentWillUnmount - 组件移除时被调用
- 典型场景: 资源释放,例如,清楚定时器
二、demo
app.js
import React , {Component} from 'react';
import Son from './son.js'
class App extends Component {
constructor(){
console.log('1:constructor')
super();
// 定义状态和属性
this.state={
num: 1,
addNum: 0,
name: 'jace'
}
}
componentWillMount(){
// 组件即渲染,不建议在此处发送ajax请求外部资源,因为可能会造成渲染的阻塞
console.log('2:componentWillMount')
}
render(){
console.log('3: render')
let {num,name} =this.state;
return(
<div>
<h1>{this.state.num}</h1>
<input type='text' value={this.state.num} onChange={(e)=>{this.changeValue(e)}} />
<hr />
<h5>{this.state.addNum}</h5>
<button onClick={()=>{this.changeAdd()}}>点击增加</button>
<hr />
<Son num={num} name={name}/>
</div>
)
}
componentDidMount(){
// 请求外部资源
console.log('4:componentDidMount')
}
// 刷新
shouldComponentUpdate(){
// 决定是否重绘,可用于性能优化
console.log('1: shouldComponentUpdate')
return true
}
componentWillUpdate(){
console.log('2: componentWillUpdate')
}
componentDidUpdate(){
console.log('3: componentDidUpdate')
}
changeValue(e){
this.setState({
num: e.target.value
})
}
changeAdd(){
let add= this.state.addNum+1;
this.setState({
addNum: add
})
}
}
export default App;
控制台打印如下
1:constructor
2:componentWillMount
3: render
4:componentDidMount
1: shouldComponentUpdate
2: componentWillUpdate
3: render
3: componentDidUpdate
son.js
import React,{Component} from 'react'
class Son extends Component {
constructor(props){
super(props);
this.state={
}
}
render(){
console.log(this.props)
let {num,name}=this.props
return (
<div>
<h1>{num}</h1>
<h1>{name}</h1>
</div>
)
}
}
export default Son