目錄
生命週期
該方法在render 之前被調用,也就是說在這個方法當中無法取得到真實的DOM 元素。
該方法是在 render 之後被調用,也就是這個方法可以直接取得到真實的 DOM 元素。
當改變元件的props 或state 時候會觸發
方法接受一個參數
方法接受兩個參數
Unmounting
componentWillUnmount
重新渲染的执行顺序
首頁 web前端 js教程 React中生命週期使用詳解

React中生命週期使用詳解

May 24, 2018 pm 02:21 PM
react 使用 詳解

這次帶給大家React中生命週期使用詳解,React中生命週期使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

生命週期

React 是一個由虛擬 DOM 渲染成真實 DOM 的過程,這個過程稱為元件的生命週期。 React 把這個週期分成三個階段,每個階段都提供了 will 和 did 兩種處理方式,will 是指發生前,did 是指發生後。

  • Mounting:元件渲染過程

    • #componentWillMount()

    • componentDidMount()

  • Updating:元件更新過程

    • #componentWillReceiveProps(nextProps)

    • #shouldComponentUpdate(nextProps, nextState)

    • #componentWillUpdate(object nextProps, object nextState)

    • componentDidUpdate(object prevProps, #object prevProps

  • Unmounting:元件移除過程

    • #componentWillUnmount()

    • 這個階段沒有對應的did 方法

Mounting

指首次渲染或元件從DOM 移除後再次重新渲染,後者場景不會執行getDefaultProps

執行順序

  1. getDefaultProps

  2. #getInitialState

  3. ##componentWillMount
  4. render
  5. componentDidMount
  6. componentWillMount

該方法在render 之前被調用,也就是說在這個方法當中無法取得到真實的DOM 元素。

首次渲染前和當 state 改變時再次渲染前觸發方法。


componentDidMount

該方法是在 render 之後被調用,也就是這個方法可以直接取得到真實的 DOM 元素。

首次渲染後和當 state 發生變更再次渲染後觸發方法。

var MountingComponent = React.createClass({
    componentWillMount: function(){
        console.log(this.refs.h1) // undefined
    },
    componentDidMount: function(){
        console.log(this.refs.h1) // h1 对象
    },
    render: function(){
        return <h1 ref="h1">Lifecycle-Mounting</h1>;
    }                
})
ReactDOM.render(<MountingComponent />, document.getElementById('p1'));
登入後複製

Updating

當改變元件的props 或state 時候會觸發

執行順序

##componentWillReceiveProps
  1. shouldComponentUpdate
  2. componentWillUpdate
  3. render
  4. componentDidUpdate
  5. componentWillReceiveProps
在元件接收到一個新的prop時被呼叫。這個方法在初始化render時不會被呼叫。

方法接受一個參數

newProps: 為更新後的props

註:props 不能手動改變,正常場景是當前元件被當子元件調用,然後在父元件中改變該元件的props

shouldComponentUpdate

元件掛載之後,每次呼叫setState後都會呼叫shouldComponentUpdate判斷是否需要重新渲染元件。預設回傳true,需要重新render。在比較複雜的應用程式裡,有一些資料的改變並不影響介面展示,可以在這裡做判斷,優化渲染效率。

方法接受兩個參數

newProps:已更新的 props

newState:已更新的 state
方法必須傳回 boolen,傳回 true 則執行後面的 componentWillUpdate、render、componentDidUpdate。反之則不執行。

componentWillUpdate

在元件接收到新的props或state但還沒有render時被呼叫。在初始化時不會被呼叫。

方法接受兩個參數

nextProps:將要更新的 props

nextState:將要更新的 state

componentDidUpdate

在元件完成更新後立即呼叫。在初始化時不會被呼叫。

方法接受兩個參數

prevProps:更新前的 props

nextState:更新前的 state

var UpdatingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },           
    setNewNumber: function() {
        //当 state 发生改变的时候,state 对应的组件会重新挂载
        //会触发 componentWillUpdate、componentDidUpdate
        this.setState({data: this.state.data + 1})
    },
    //参数 newProps:已更新的 props
    componentWillReceiveProps:function(newProps) {
        console.log('Component WILL RECEIVE PROPS!', newProps)
    },        
    //参数 newProps:已更新的 props
    //参数 newState:已更新的 state  
    //必须要返回 boolen,true 则执行componentWillUpdate、render、componentDidUpdate。反之则不执行。
    shouldComponentUpdate: function(newProps, newState){
        console.log('shouldComponentUpdate',newProps, newState);
        return (newState.data > 0 && newState.data % 2 == 0);
    },                          
    //参数 nextProps:将要更新的 props
    //参数 nextState:将要更新的 state
    componentWillUpdate: function(nextProps, nextState){
        console.log(nextProps, nextState, this.refs.p1)
    },
    //参数 prevProps:更新前的 props
    //参数 nextState:更新前的 state                
    componentDidUpdate: function(prevProps, prevState){
        console.log(prevProps, prevState) 
    },
    render: function(){
        return (
            <p>
                <button onClick={this.setNewNumber}>INCREMENT</button>
                <h3>{this.state.data}</h3>
            </p>
        );
    }                
})
ReactDOM.render(<UpdatingComponent/>, document.getElementById('p2'));
登入後複製

Unmounting

在组件从 DOM 中移除的时候立刻被调用,这个阶段没有对应的 did 方法

componentWillUnmount

方法适用在父子组件的结构中,当某个条件符合的场景下,该子组件会被渲染

重新渲染的执行顺序

  1. getInitialState

  2. componentWillMount

  3. render

  4. componentDidMount

var ChildrenComponent = React.createClass({
    componentWillUnmount: function(){
        console.log('componentWillUnmount');
    },
    render: function(){
        return <h3>{this.props.myNumber}</h3>
    }
})
var UnmountingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },
    setNewNumber: function() {
        this.setState({data: this.state.data + 1})
    },
    render: function () {
        var content;
        //当条件不符合时 ChildrenComponent 会被移除,然后会触发方组件的 componentWillUnmount 方法
        //当条件重新符合时,会重新渲染组件 ChildrenComponent
        if(this.state.data % 2 == 0){
            content = <ChildrenComponent myNumber = {this.state.data}></ChildrenComponent>;
        } else {
            content = <h3>{this.state.data}</h3>;
        }
        return (
            <p>
                <button onClick = {this.setNewNumber}>INCREMENT</button>
                {content}
            </p>
        );
    }
})
ReactDOM.render(<UnmountingComponent/>, document.getElementById('p3'));
登入後複製

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

react实现选中li高亮步骤详解

PromiseA+的实现步骤详解


以上是React中生命週期使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

crystaldiskmark是什麼軟體? -crystaldiskmark如何使用? crystaldiskmark是什麼軟體? -crystaldiskmark如何使用? Mar 18, 2024 pm 02:58 PM

crystaldiskmark是什麼軟體? -crystaldiskmark如何使用?

foob​​ar2000怎麼下載? -foobar2000怎麼使用 foob​​ar2000怎麼下載? -foobar2000怎麼使用 Mar 18, 2024 am 10:58 AM

foob​​ar2000怎麼下載? -foobar2000怎麼使用

Win11管理員權限取得詳解 Win11管理員權限取得詳解 Mar 08, 2024 pm 03:06 PM

Win11管理員權限取得詳解

網易信箱大師怎麼用 網易信箱大師怎麼用 Mar 27, 2024 pm 05:32 PM

網易信箱大師怎麼用

百度網盤app怎麼用 百度網盤app怎麼用 Mar 27, 2024 pm 06:46 PM

百度網盤app怎麼用

Oracle SQL中的除法運算詳解 Oracle SQL中的除法運算詳解 Mar 10, 2024 am 09:51 AM

Oracle SQL中的除法運算詳解

BTCC教學:如何在BTCC交易所綁定使用MetaMask錢包? BTCC教學:如何在BTCC交易所綁定使用MetaMask錢包? Apr 26, 2024 am 09:40 AM

BTCC教學:如何在BTCC交易所綁定使用MetaMask錢包?

教你使用 iOS 17.4「失竊裝置保護」新進階功能 教你使用 iOS 17.4「失竊裝置保護」新進階功能 Mar 10, 2024 pm 04:34 PM

教你使用 iOS 17.4「失竊裝置保護」新進階功能

See all articles