一、生命周期 (旧版)
一个组件从开始到死亡的过程中,会触发该生命周期中的事件,把这个事件的生命周期函数暴露出来使用,这个函数称之为生命周期函数
引入图示:
-
mouting阶段
(只执行一次)constructor
初始化数据componentWillMount
挂载之前render
渲染 每次渲染时要处理的逻辑componentDidMount
请求数据 获取到真实的DOM
constructor(){ // 初始化数据 super(); this.state = {} console.log(1) } componentWillMount(){ console.log('挂载之前') } render(){ // 第一次渲染 console.log('渲染') } componentDidMount(){ // 请求数据 console.log('挂载之后') } 复制代码
-
updating阶段
shouldComponentUpdate
性能优化 此函数必须有返回值,返回布尔值 默认为true 返回true 即更新 返回false 即不更新componentWillUpdate
数据更新之前render
数据渲染 (不要使用setState)componentDidUpdate
数据更新之后
// updating阶段 shouldComponentUpdate(){ // 性能优化 // 此函数必须有返回值,返回布尔值 默认为true console.log('should'); return true; // 返回true 即更新 返回false 即不更新 } componentWillUpdate(){ console.log('更新之前') } componentDidUpdate(){ console.log('更新之后') } myClick=()=>{ let {num} = this.state; num++; this.setState({num}) } render(){ console.log('渲染') return( <div id="box"> <button onClick = {this.myClick} >{this.state.num}</button> </div> ) } 复制代码
- 注意:updating阶段不要使用setState,否则会死循环
componentWillReceiveProps
父级数据发生变化
-
unmouting阶段
componentWillUnmout
当组件死亡时触发(卸载、跳路由、关定时器、数据重置、变量置空、清除事件)
生命周期 (新版)
参考:blog.hhking.cn/2018/09/18/…
引入两个新的API:
getDerivedStateFromProps()
getSnapshotBeforeUpdate()
替代:
componentWillMount()
componentWillReceiveProps()
componentWillUpdate()
import React, { Component } from 'react';
import reactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {
num:0
}
}
static getDerivedStateFromProps(nextProps, prevState){
/*
nextProps: 新接收的 props
prevState: 当前的 state
*/
// console.log(nextProps)
// console.log(prevState);
console.log('123')
return(
<div></div>
)
}
componentDidMount(){
console.log('挂载之后')
}
shouldComponentUpdate(){
console.log('性能优化')
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState){
/*
两个参数
- prevProps 表示更新前的 props
- prevState 表示更新前的 state
1. getSnapshotBeforeUpdate一定要有返回值
2. 此函数的返回值是componentDidUpdate函数的第三个参数
3. 这个函数必须要配合 componentDidUpdate() 一起使用。
*/
console.log('更新之前')
return null;
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log('更新之后')
}
myClick = () => {
let { num } = this.state;
num++;
this.setState({ num })
}
render() {
console.log('渲染')
return (
<div>
{this.state.num}
<br/>
<Child num={this.state.num} myClick={this.myClick}/>
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
num:props.num
}
}
// static getDerivedStateFromProps(nextProps, prevState){
// console.log('123')
// // console.log(nextProps)
// // console.log(prevState);
// return(
// <div></div>
// )
// }
render() {
return (
<button
onClick={this.props.myClick}
>{this.props.num}</button>
);
}
}
export default App;
reactDOM.render(<App />, document.getElementById('root'));
复制代码