在本章節中我們将讨論 React 元件的生命周期。
元件的生命周期可分成三個狀态:
Mounting(挂載):已插入真實 DOM
Updating(更新):正在被重新渲染
Unmounting(解除安裝):已移出真實 DOM

當元件執行個體被建立并插入 DOM 中時,其生命周期調用順序如下:
<code>constructor()</code>: 在 React 元件挂載之前,會調用它的構造函數。
<code>getDerivedStateFromProps()</code>: 在調用 render 方法之前調用,并且在初始挂載及後續更新時都會被調用。
<code>render()</code>: render() 方法是 class 元件中唯一必須實作的方法。
<code>componentDidMount()</code>: 在元件挂載後(插入 DOM 樹中)立即調用。
render() 方法是 class 元件中唯一必須實作的方法,其他方法可以根據自己的需要來實作。
這些方法的詳細說明,可以參考官方文檔。
每當元件的 state 或 props 發生變化時,元件就會更新。
當元件的 props 或 state 發生變化時會觸發更新。元件更新的生命周期調用順序如下:
<code>getDerivedStateFromProps()</code>: 在調用 render 方法之前調用,并且在初始挂載及後續更新時都會被調用。根據 shouldComponentUpdate() 的傳回值,判斷 React 元件的輸出是否受目前 state 或 props 更改的影響。
<code>shouldComponentUpdate()</code>:當 props 或 state 發生變化時,shouldComponentUpdate() 會在渲染執行之前被調用。
<code>getSnapshotBeforeUpdate()</code>: 在最近一次渲染輸出(送出到 DOM 節點)之前調用。
<code>componentDidUpdate()</code>: 在更新後會被立即調用。
當元件從 DOM 中移除時會調用如下方法:
<code>componentWillUnmount()</code>: 在元件解除安裝及銷毀之前直接調用。
以下是一個目前時間的執行個體,每秒更新:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
componentWillUnmount() {
clearInterval(this.timerID);
tick() {
this.setState({
date: new Date()
});
render() {
return (
<div>
<h1>Hello, Runoob!</h1>
<h2>現在時間是:{this.state.date.toLocaleTimeString()}.</h2>
</div>
ReactDOM.render(
<Clock />,
document.getElementById('root')
以下執行個體在 Hello 元件加載以後,通過 componentDidMount 方法設定一個定時器,每隔100毫秒重新設定元件的透明度,并重新渲染:
class Hello extends React.Component {
this.state = {opacity: 1.0};
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
opacity: opacity
}.bind(this), 100);
render () {
<div style={{opacity: this.state.opacity}}>
Hello {this.props.name}
<Hello name="world"/>,
document.body
以下執行個體初始化 <b>state</b> , <b>setNewnumber</b> 用于更新 <b>state</b>。所有生命周期在 <b>Content</b> 元件中。
class Button extends React.Component {
this.state = {data: 0};
this.setNewNumber = this.setNewNumber.bind(this);
setNewNumber() {
this.setState({data: this.state.data + 1})
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data}></Content>
class Content extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
console.log('Component DID MOUNT!')
componentWillReceiveProps(newProps) {
console.log('Component WILL RECEIVE PROPS!')
shouldComponentUpdate(newProps, newState) {
return true;
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
console.log('Component WILL UNMOUNT!')
<h3>{this.props.myNumber}</h3>
<Button />
</div>,
document.getElementById('example')