標籤雲

搜尋此網誌

2016/07/06

Component Lifecycle API

Component 的生命週期有
建構, 掛載(mount), 渲染(render), 更新(update), 卸載(unmount), 銷毀( destroy)等

你可以在各生命週期中插入執行自定的程式碼來達到更細膩的控制

Mounting Cycle

constructor(object props)
從父 element 初始化 props, 此時我們也可以順便初始化 state
在 ES5 用的是 getDefaultProps / getInitialState 的方法
var MyComponent = React.createClass({
  propTypes: {
    text: React.PropTypes.string,
    anotherProp: React.PropTypes.string.isRequired,
    //以此類推...
  },
  getDefaultProps: function() {
    return {
      anotherProp: 'default value'
    };
  },
  getInitialState: function(){
    return { 
      key1: 'value1', 
      key2: null
    };
  },
  //...
});

在 ES6 則是用 constructor 的方式
至於 defaultProps 是在 Component 內用一個 static 變數來處理
import React, { PropTypes, Component } from 'react';
class MyComponent extends Component {
  static defaultProps = {
    text: 'default value',
  };
  static propTypes = {
    text: PropTypes.string.isRequired,
  };
  constructor(props){
    super(props);
    //initial state
    this.state = { 
      key1: 'value1', 
      key2: null
    };
  }
  //...
}

componentWillMount()
在第一次 render 發生前被呼叫, 此方法只會被呼叫一次

render() -> React Element
render 必須 return 一個 React Element (或是 null 表示不顯示任何東西)
在第一次 render 之前這個 element 不會有任何 native UI

componentDidMount()
在第一次 render 發生後被呼叫, 此方法只會被呼叫一次
此時這個 element 的 native UI 已經完成 render, 可以透過 this.refs 直接操作
如果需要進行非同步 API 呼叫或是用 setTimeout 執行 delayed code, 一般是在這裡進行


Updating Cycle

componentWillReceiveProps(object nextProps)
父 component 傳入了新的 props, 所以 component 即將重新渲染 (re-render)
在 render 方法被呼叫前我們可以用 this.setState() 更新 component 內部狀態

shouldComponentUpdate(object nextProps, object nextState) -> boolean
根據新的 props 跟 state, 該 component 必須決定是否該重新渲染
基底類別的 shouldComponentUpdate 實作總是會回傳 true
我們可以 override 這個方法並檢查每個 props 跟 state 是否已被更動(例如對每個 key/value 做 equal 檢查), 若回傳 false 就不會重新渲染

componentWillUpdate(object nextProps, object nextState)
componentWillUpdate 代表 component 此時已經確定要重新渲染
這時我們就不該用 this.setState() 改變狀態, 因為已經在進行更新了

render() -> React Element
既然要重新渲染當然就會再呼叫 render

componentDidUpdate(object prevProps, object prevState)
重新渲染完成後, 該 component 已經更新了從 render() 回傳來的 React Element


最後是卸載的部分
Uumount

componentWillUnmount()
若有使用 Timer, 卸載前應該清除以避免 Fatal
clearInterval/clearTimeout/clearImmediate

相關資料:
React Native Express - Lifecycle API
React - Reusable Components
React Native 中组件的生命周期

沒有留言: