iT邦幫忙

0

React Class Component 生命週期 - Mounting 篇

挑戰 React 第二十一篇

主要分成以下四大類:

  1. Mounting
  2. Updating
  3. Unmounting
  4. Error Handling

Mounting

Mounting 生命週期

Mounting 有四個生命週期

  1. Constructor

    • 初始化 state
    • 事件綁定
  2. static getDerivedStateFromProps(nextProps, prevState)
    自己沒用過這個方法,但官網表示:

    • 是一個 static 靜態函數,因此無法操作 class 中的屬性 (ex. this.state)
    • 無條件的根據 prop 更新內部 state,也就是只要有傳入prop 值, 就更新state
    • 只有 prop 和 state 不同時才更新 state
  3. render()

    • 回傳 React Element
  4. componentDidMount

    • 取的 API 資料
    • 使用 setState()

實際範例

利用 console.log() 印出生命週期

import React, { Component } from 'react';

class LifeCycle extends Component {
  constructor(props) {
    super(props);
  
    this.state = {
       test: 'aaaa',
    }
    console.log('Constructor');
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log('getDerivedStateFromProps');
    // 回傳 null 表示 state 無異動
    return null;
  }

  componentDidMount() {
    console.log('componentDidMount');
  }
  
  render() {
    console.log('render');
    return (
      <div>
        LifeCycle Test
      </div>
    )
  }
}

export default LifeCycle;

網頁呈現

有 Child Componet 的範例

import React, { Component } from 'react';
import ChildLifeCycle from './ChildLifeCycle';

class ParentLifeCycle extends Component {
  constructor(props) {
    super(props);
  
    this.state = {
       test: 'aaaa',
    }
    console.log('Parent Constructor');
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log('Parent getDerivedStateFromProps');
    // 回傳 null 表示 state 無異動
    return null;
  }

  componentDidMount() {
    console.log('Parent componentDidMount');
  }
  
  render() {
    console.log('Parent render');
    return (
      <div>
        Parent LifeCycle
        <ChildLifeCycle />
      </div>
    )
  }
}

export default ParentLifeCycle
import React, { Component } from 'react';

class ChildLifeCycle extends Component {
  constructor(props) {
    super(props);
  
    this.state = {
       test: 'aaaa',
    }
    console.log('Child Constructor');
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log('Child getDerivedStateFromProps');
    // 回傳 null 表示 state 無異動
    return null;
  }

  componentDidMount() {
    console.log('Child componentDidMount');
  }
  
  render() {
    console.log('Child render');
    return (
      <div>
        Child LifeCycle
      </div>
    )
  }
}

export default ChildLifeCycle;

網頁呈現

參考 React 官方網站連結


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言