React生命周期详解
import React, { Component } from 'react'
export default class index extends Component {
//1[constructor].做一些组件的初始化工作,如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
constructor(props) {
super(props);
// 不要在这里调用 this.setState()
this.state={count:1};
this.handleClick = this.handleClick.bind(this);
console.log('构造函数:constructor');
}
handleClick(){
// console.log(this.props);
this.setState({count:this.state.count+1})
}
//2.[getDerivedStateFromProps].会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。
//3.[shouldComponentUpdate].当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。返回值默认为 true。首次渲染或使用 forceUpdate() 时不会调用该方法。
//4.[render].根据组件的props和state(无论两者的重传递和重赋值是否有变化,都可以引起组件重新render)(render是纯函数)
render() {
//return 一个React元素(描述组件,即UI),不负责组件实际渲染工作,之后由React自身根据此元素去渲染出页面DOM。
console.log('render');
return (
<div>
<h1>React生命周期</h1>
<button onClick={()=>{
this.handleClick()
}}>函数1</button>
<p>{this.state.count}</p>
<button onClick={()=>{
console.log('强制渲染:forceUpdate()')
this.forceUpdate()//强制让组件重新渲染调用render()
}}>强制渲染</button>
</div>
)
}
/*5.[getSnapshotBeforeUpdate()].在最近一次渲染输出(提交到 DOM 节点)之前调用。
它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。
此生命周期方法的任何返回值将作为参数传递给 componentDidUpdate()。*/
/*React 更新 DOM 和 refs(在此React自身根据此元素去渲染出页面DOM)*/
//6[componentDidMount].会在组件第一次挂载后(插入 DOM 树中)立即调用,且只会被调用一次。
componentDidMount(){
console.log('组件第一次挂载:componentDidMount');
}
//7[componentDidUpdate].会在更新后会被立即调用。首次渲染不会执行此方法,此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState这两个参数指的是组件更新前的props和state
componentDidUpdate(){
console.log('更新后调用:componentDidUpdate');
}
//8[componentWillUnmount].会在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作,例如,清除 timer。
componentWillUnmount(){
console.log('组件卸载及销毁之前:componentWillUnmount');
}
}

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

浙公网安备 33010602011771号