【Day06】生命周期 Lifecycle(Class Component)

React 元件拥有从产生、渲染
到被移除解放资源的各个阶段
称之为生命周期(Lifecycle)

Class Component 生命周期

  • Mount:初始化阶段(只执行一次)
  • Update:组件更新阶段
  • Unmount:组件卸载阶段(只执行一次)

Mount

  • constructor
  • getDerivedStateFromProps
  • render
  • componentDidMount

Update

  • getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpdate

Unmount

  • componentWillUnmount

生命周期方法

  • constructor:创建 class component 时必定呼叫的方法,进行资料宣告、初始化、预备、函式绑定的地方
  • getDerivedStateFromProps:初始化时、props 或 state 改变时执行
class App extends React.Component{
	...
	static getDerivedStateFromProps(props, state){
		return{
			age: 23
		}
	}
}
  • shouldComponentUpdate:用於避免没必要的更新,以达到优化效果
  • render:将 HTML 输出到 DOM
  • getSnapshotBeforeUpdate:更新前执行,让组件在DOM发生变化前捕获一些信息(如滚动位置),用意是把更新前的最後一刻DOM的状况纪录下来
  • componentDidMount
    • 第一次渲染(安装完毕)後唯一触发的生命周期函数,只会执行一次
    • render 完毕後呼叫,用於处理数据,比方说传入API资料,
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

一开始要就触发的东西,一般都放在 componentDidMount 里面执行。

  • componentDidUpdate:组件更新完毕後执行
  • componentWillUnmount:元件被移除时呼叫一次,进行一些收尾工作,比方说移除新增的元素、监听事件与定时器
  • componentDidCatch:捕获组件错误信息
componentDidCatch(error, info)
  • static getDerivedStateFromError
class App extends React.Component{
	...
	async componentDidMount(){
		const user = await fetch("/api/user").then(res => json());
		this.setState({ user });
	}
}
  • forceUpdate:直接调用render()强制重新渲染组件,包含子组件也会重新渲染

生命周期参考图片
生命周期参考图片 | 图片来源

参考资料:

【React.js入门 - 16】 React生命周期(1/4): Mount(上)- 在渲染以前


<<:  Day10-D3 Transition 动画

>>:  Day22 测试写起乃 - Sidekiq Testing

[Day28]Hashmat the brave warrior

上一篇介绍了Vito'sfamily,这一题题目讲那麽多,但其实主要是考我们找出中位数,并让每个数都...

Day19 弱点扫描软件安装与使用注意事项

我们在前几篇文章介绍如何收集资料、并介绍几个好用的工具如 nmap、Nikto、WPScan,透过这...

【Day3】不可貌相的JS变数型别:基本型别

俗话说:「人不可貌相,海水不可斗量。」就像我们看到郭靖傻不楞登,怎麽知道他武功高强。杨康外表英俊,...

Day06:绝对要有的Git观念与习惯

一、前言   先前有提到,我在转职後、进到现职公司前,其实还有录取过另外一份PHP後端工程师之职缺,...

数位变革

在疫情爆发之前,一切的一切看似都非常的正常,但是在爆发之後,所有的一切都被疫情给打乱了,并且所有的秩...