1. 程式人生 > 其它 >React類式元件生命週期

React類式元件生命週期

React類式元件生命週期(新)

React 類式元件生命週期

1. 首次載入時
1) contructor

類式元件的構造器,可在構造器中初始化元件狀態( state )

2) getDerivedStateFromProps

state的值在任何時候都取決於props( props變化時更新state ),接收兩個引數propsstate

3) render

渲染函式,返回vnode

4) componentDidMount

元件第一次被渲染到DOM中,可在此鉤子中設定定時器,呼叫AJAX

2. 更新時
1) getDerivedStateFromProps
2) shouldComponentUpdate

根據return的布林值

決定是否更新元件

3) render
4) getSnapshotBeforeUpdate

獲取更新前的快照,其返回值預設作為componentDidUpdate第三個引數

5) componentDidUpdate

元件更新之後,其可接收三個引數未更新前的props未更新前的stategetSnapshotBeforeUpdate的返回值

3. 解除安裝時
1) componentWillUnmount

元件即將解除安裝之前呼叫的鉤子,可在此階段銷燬定時器

4. Demo
import { Component, Fragment } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';

class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = { title: 'This is a initial demo.' };
    console.log('constructor');
  }

  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps');
    return { subTitle: props.subTitle };
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  getSnapshotBeforeUpdate() {
    console.log('getSnapshotBeforeUpdate');
    return { snapshotRes: 'getSnapshotBeforeUpdate' };
  }

  shouldComponentUpdate() {
    console.log('shouldComponentUpdate');
    return true;
  }

  componentDidUpdate(preProps,preState,snapshotValue) {
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  /**
   * 使用箭頭函式,防止找不到this
   */
  updateComponent = () => {
    this.forceUpdate();
  }

  unmountComponent = () => {
    unmountComponentAtNode(document.querySelector('#app'));
  }

  render() {
    console.log('render');
    const { title, subTitle } = this.state;
    return (
      <Fragment>
        <h1>{ title }</h1>
        <h2>{ suTitle }</h2>
        <button onClick={ this.updateComponent }>Force update</button>
        <button onClick={ this.unmountComponent }>Unmount component</button>
      </Fragment>
    )
  }
}

render(<Demo suTitle="Alison" />, document.querySelector('#app'));