React組件生命周期詳解

React組件生命周期

constructor( ) 組織要領

constructor是ES6對類的默許要領,經由過程 new 敕令天生對象實例時自動挪用該要領。而且,該要領是類中必需有的,假如沒有顯現定義,則會默許增加空的constructor( )要領。當存在constructor的時刻⚠️必需手動挪用super要領。
在constructor中假如要接見this.props須要傳入props,示例以下:

class MyClass extends React.component{
    constructor(props){
        super(props); // 聲明constructor時必需挪用super要領
        console.log(this.props); // 能夠平常接見this.props
    }
}

constructor 常用來初始化state

class MyClass extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            list: this.props.List
        };
    }
}

Class靜態要領實例屬性 初始化state

class ReactCounter extends React.Component {
    state = {
      list: []
    };
}

詳細文章可見Class-的靜態要領

componentWillMount() 組件掛載之前

在組件掛載之前挪用且全局只挪用一次。假如在這個鈎子里能夠setState,render后能夠看到更新后的state,不會觸發反覆襯着。該生命周期能夠提議異步要求,並setState。(React v16.3后燒毀該生命周期,能夠在constructor中完成設置state

render()  襯着組件

render是一個React組件必需定義的生命周期,用來襯着dom。⚠️不要在render內里修正state,會觸發死輪迴致使棧溢出。render必需返回reactDom

render() {
    const {nodeResultData: {res} = {}} = this.props;
    if (isEmpty(res)) return noDataInfo;
    const nodeResult = this.getNodeResult(res);
    return (
        <div className="workspace-dialog-result">
            {nodeResult}
        </div>
    );

componentDidMount() 組件掛載完成后

在組件掛載完成后挪用,且全局只挪用一次。能夠在這裏運用refs,獵取實在dom元素。該鈎子內也能夠提議異步要求,並在異步要求中能夠舉行setState。

componentDidMount() {
    axios.get('/auth/getTemplate').then(res => {
        const {TemplateList = []} = res;
        this.setState({TemplateList});
    });
}

componentWillReceiveProps (nextProps ) props行將變化之前

props發作變化以及父組件從新襯着時都邑觸發該生命周期,在該鈎子內能夠經由過程參數nextProps獵取變化后的props參數,經由過程this.props接見之前的props。該生命周期內能夠舉行setState。(React v16.3后燒毀該生命周期,能夠用新的周期 static getDerivedStateFromProps 替代)

shouldComponentUpdate(nextProps, nextState) 是不是從新襯着

組件掛載以後,每次挪用setState后都邑挪用shouldComponentUpdate推斷是不是須要從新襯着組件。默許返回true,須要從新render。返回false則不觸發襯着。在比較複雜的運用里,有一些數據的轉變並不影響界面展現,能夠在這裏做推斷,優化襯着效力。

componentWillUpdate(nextProps, nextState)

shouldComponentUpdate返回true或許挪用forceUpdate以後,componentWillUpdate會被挪用。不能在該鈎子中setState,會觸發反覆輪迴。(React v16.3后燒毀該生命周期,能夠用新的周期 getSnapshotBeforeUpdate )

componentDidUpdate() 完成組件襯着

除了初次render以後挪用componentDidMount,別的render完畢以後都是挪用componentDidUpdate。該鈎子內setState有可能會觸發反覆襯着,須要自行推斷,否則會進入死輪迴。

componentDidUpdate() {
    if(condition) {
        this.setState({..}) // 設置state
    } else {
        // 不再設置state
    }
}

componentWillUnmount() 組件行將被卸載

組件被卸載的時刻挪用。平常在componentDidMount內里註冊的事宜須要在這裏刪除。

生命周期圖

《React組件生命周期詳解》

完全的生命周期示例

class LifeCycle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {str: "hello"};
    }

    componentWillMount() {
        alert("componentWillMount");
    }

    componentDidMount() {
        alert("componentDidMount");
    }

    componentWillReceiveProps(nextProps) {
        alert("componentWillReceiveProps");
    }

    shouldComponentUpdate() {
        alert("shouldComponentUpdate");
        return true;        // 記得要返回true
    }

    componentWillUpdate() {
        alert("componentWillUpdate");
    }

    componentDidUpdate() {
        alert("componentDidUpdate");
    }

    componentWillUnmount() {
        alert("componentWillUnmount");
    }
    render() {
        alert("render");
        return(
            <div>
                <span><h2>{parseInt(this.props.num)}</h2></span>
                <br />
                <span><h2>{this.state.str}</h2></span>
            </div>
        );
    }
}

React v16.3 新到場的生命周期 (轉載)

react v16.3刪掉以下三個生命周期

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

新增兩個生命周期

  • static getDerivedStateFromProps
  • getSnapshotBeforeUpdate

static getDerivedStateFromProps

  • 觸發時候:在組件構建以後(假造dom以後,現實dom掛載之前) ,以及每次獵取新的props以後。
  • 每次吸收新的props以後都邑返回一個對象作為新的state,返回null則申明不須要更新state.
  • 合營componentDidUpdate,能夠掩蓋componentWillReceiveProps的一切用法
class Example extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // 沒錯,這是一個static
  }
}

getSnapshotBeforeUpdate

  • 觸發時候: update發作的時刻,在render以後,在組件dom襯着之前。
  • 返回一個值,作為componentDidUpdate的第三個參數。
  • 合營componentDidUpdate, 能夠掩蓋componentWillUpdate的一切用法。
class Example extends React.Component {
    getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
    }
}
    原文作者:飛翔的荷蘭人
    原文地址: https://segmentfault.com/a/1190000015025236
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞