4.4.life cycle

可分為實例化, 存在期, 銷毀&清理期:

  • 1.Initialization (實例化):

    • 一個實例初次被創建時所調用的生命週期方法, 與其他各個後續實例被創建時所調用的方法略有不同.

      • getDefaultProps():

        • 只有第一次創建時會被調用, 在創建任意组件时,我们可以通过getDefaultProps方法给他定義一些属性.

        • 当我们需要在render方法使用某些數據時,可以在getDefaultProps() 函数中定義這個属性,然後通过{this.props.style}來進行獲取:

        • 對象或數組都會在所有實例中共享

          class CustomizableText extends Component {
          constructor(props) {
            super(props);
            this.style = {
            };
          }
          render() {
            return (
              <Text style ={[this.props.style]} >Hello</Text>
            )
          }
          };
          CustomizableText.propTypes = {
          style: React.PropTypes.Text.isRequred,
          };
      • getInitialState():

        • 當物件被調用時此方法會在寫入 DOM 之前被觸發,通常用來管理狀態的元件可以用這個方法初始化一些資料,用來初始化每個實例的state, 可以訪問到this.props

        • 當components完成render後, 可使用setState改變this.state的內容, 此時會重新render以達成動態改變畫面的效果

        this.setState({
          mykey:'my new value'
        });
        • 新版改為以下寫法:

      • componentWillMount():

        • render被調用前最後可以修改組件state的最後機會

        • 这個时候DOM结構已经渲染了.這個時候就可以初始化其他框架的設置了,如果利用jQuery绑定事件等等.

      • render():

        • 此函數將創建虛擬DOM

        • 是唯一一個必須的方法

        • 必須滿足下面幾點:

        • render返回的並不是真正的DOM, 而是一個虛擬的表現, React將會將他與真實的DOM做對比, 來判斷是否有必要作出修改.

      • componentDidMount():

        • 當元件被寫入 DOM 之後觸發。當初始化需要操作 DOM 元素就可以用這個方法

        • 可以在這邊使用getDOMNode()

  • 2.存在期

    • componentWillReceiveProps(nextProps)

    • shouldComponentUpdate(nextProps, nextState)

    • componentWillUpdate(nextProps, nextState)

    • render()

    • componentDidUpdate(prevProps, prevState)

  • 3.Unmounting (銷毀&清理期):

    • componentWillUnmount

reference:

Last updated

Was this helpful?