搜尋
首頁web前端前端問答react生命週期的三個過程是什麼

react生命週期的三個過程:1、掛載期,也叫實例化期,是一個元件實例初次被創建的過程;2、更新期,也稱為存在期,是元件在創建之後再次渲染的過程;3、卸載期,也被稱為銷毀期,是元件在使用完後被銷毀的過程。

react生命週期的三個過程是什麼

本教學操作環境:Windows10系統、react17.0.1版、Dell G3電腦。

react生命週期的三個過程是什麼

React的生命週期從廣義上分為三個階段:掛載、渲染、卸載

從出生到成長,最後到死亡,這個過程的時間可以理解為生命週期。 React的生命週期同理也是這麼一個過程。

React的生命週期分為三個階段:掛載期(也稱為實例化期)、更新期(也叫存在期)、卸載期(也叫銷毀期)。在每個週期中React都提供了一些鉤子函數。

生命週期的描述如下:

  • #掛載期:一個元件實例初次北創建的過程。

  • 更新期間:元件在建立後再次渲染的過程。

  • 卸載期:元件在使用完後被銷毀的過程。

元件的掛載:

#元件在第一次建立後,進行第一次的渲染為掛載期。掛載期有的一些方法會被依序觸發,列舉如下:

  • constructor(建構函數,初始化狀態值)
  • getInitialState(設定狀態機)
  • getDefaultProps(取得預設的props)
  • UNSAFE_componentWillMount(首次渲染前執行)
  • render(渲染元件)
  • componentDidMount(render渲染之後執行的動作)
//组件挂载import React from 'react';import ReactDOM from 'react-dom';class HelloWorld extends React.Component{
    constructor(props) {
        super(props);
        console.log("1,构造函数");
        this.state={};
        console.log("2,设置状态机");
    }
    static defaultProps={
        name:"React",
    }
    UNSAFE_componentWillMount(nextProps, nextState, nextContext) {
        console.log("3,完成首次渲染前调用");
    }
    render() {
        console.log("4,组件进行渲染");
        return (
            <p>
                </p><p>{this.props.name}</p>
            
        )
    }
    componentDidMount() {
        console.log("5,componentDidMount render渲染后的操作")
    }}ReactDOM.render(<helloworld></helloworld>, document.getElementById('root'));

react生命週期的三個過程是什麼

元件的更新:
元件更新,指的是元件初次渲染後,進行了元件狀態的改變。 React在生命週期中的更新過程包括以下幾個方法:

  • UNSAFE_componentWillReceiveProps :當父元件更新子元件state時,該方法會被呼叫。
  • shouldComponentUpdate : 方法決定元件state或props的改變是否需要重新渲染元件。
  • UNSAFE_componentWillUpdate : 在元件接受新的state或props時,即將重新渲染前呼叫該方法,和UNSAFE_componentWillMount方法類似。
  • componentDidUpdate : 在元件重新渲染後呼叫方法,和componentDidMount方法類似。
//组件更新class HelloWorldFather extends React.Component{
    constructor(props) {
        super(props);
        this.updateChildProps=this.updateChildProps.bind(this);
        this.state={  //初始化父组件
            name:"React"
        }
    }
    updateChildProps(){  //更新父组件state
        this.setState({
            name:"Vue"
        })
    }
    render() {
        return (
            <p>
                <helloworld></helloworld>  {/*父组件的state传递给子组件*/}
                <button>更新子组件props</button>
            </p>
        )
    }}class HelloWorld extends React.Component{
    constructor(props) {
        super(props);
        console.log("1,构造函数");
        console.log("2,设置状态机")
    }
    UNSAFE_componentWillMount() {
        console.log("3,完成首次渲染前调用");
    }
    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        console.log("6,父组件更新子组件时调用该方法");
    }
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        console.log("7,决定组件props或者state的改变是否需要重新进行渲染");
        return true;
    }
    UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
        console.log("8,当接收到新的props或state时,调用该方法");
    }
    render() {
        console.log("4,组件进行渲染");
        return (
            <p>
                </p><p>{this.props.name}</p>
            
        )
    }
    componentDidMount() {
        console.log("5,componentDidMount render后的操作");
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log("9,组件被重新选然后调用该方法");
    }}ReactDOM.render(<helloworldfather></helloworldfather>,document.getElementById("root"));

react生命週期的三個過程是什麼
點選「更新子元件props」後:
react生命週期的三個過程是什麼

元件的卸載:
生命週期的最後一個過程為組件卸載期,也稱為組件銷毀期。這個過程主要涉及一個 方法,即componentWillUnmount,當元件從DOM樹刪除的時候呼叫該方法。

//组件卸载class HelloWorldFather extends React.Component{
    constructor(props) {
        super(props);
        this.updateChildProps=this.updateChildProps.bind(this);
        this.state={  //初始化父组件
            name:"React"
        }
    }
    updateChildProps(){  //更新父组件state
        this.setState({
            name:"Vue"
        })
    }
    render() {
        return (
            <p>
                <helloworld></helloworld>  {/*父组件的state传递给子组件*/}
                <button>更新子组件props</button>
            </p>
        )
    }}class HelloWorld extends React.Component{
    constructor(props) {
        super(props);
        console.log("1,构造函数");
        console.log("2,设置状态机")
    }
    UNSAFE_componentWillMount() {
        console.log("3,完成首次渲染前调用");
    }
    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        console.log("6,父组件更新子组件时调用该方法");
    }
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        console.log("7,决定组件props或者state的改变是否需要重新进行渲染");
        return true;
    }
    UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
        console.log("8,当接收到新的props或state时,调用该方法");
    }
    delComponent(){  //添加卸载方法
        ReactDOM.unmountComponentAtNode(document.getElementById("root"));
    }
    render() {
        console.log("4,组件进行渲染");
        return (
            <p>
                </p><p>{this.props.name}</p>
                <button>卸载组件</button>  {/*声明卸载按钮*/}
            
        )
    }
    componentDidMount() {
        console.log("5,componentDidMount render后的操作");
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log("9,组件被重新选然后调用该方法");
    }
    componentWillUnmount() {  //组件卸载后执行
        console.log("10,组件已被卸载");
    }}ReactDOM.render(<helloworldfather></helloworldfather>,document.getElementById("root"));

react生命週期的三個過程是什麼
點選卸載按鈕後:
react生命週期的三個過程是什麼

#總覽元件生命週期:
react生命週期的三個過程是什麼

【相關推薦:javascript影片教學web前端

以上是react生命週期的三個過程是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解usestate():綜合反應國家管理指南了解usestate():綜合反應國家管理指南Apr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

使用React的優點是什麼?使用React的優點是什麼?Apr 25, 2025 am 12:16 AM

ReactispupularduetoItsOmpontement,基於虛擬,虛擬詞,Richecosystem和declarativedation.1)基於組件的harchitectureallowslowsforreusableuipieces。

在React中調試:識別和解決共同問題在React中調試:識別和解決共同問題Apr 25, 2025 am 12:09 AM

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

反應中的usestate()是什麼?反應中的usestate()是什麼?Apr 25, 2025 am 12:08 AM

usestate()inrectallowsStateMagementionInfunctionalComponents.1)ITSIMPLIFIESSTATEMAGEMENT,MACHECODEMORECONCONCISE.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousvalue,deveingingStaleStateissues.3)

usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤Apr 24, 2025 pm 05:13 PM

selectUsestate()forsimple,獨立的variables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleupDatesLikeToggGlikGlingaBglingAboolAboolAupDatingacount.2

使用usestate()管理狀態:實用教程使用usestate()管理狀態:實用教程Apr 24, 2025 pm 05:05 PM

useState優於類組件和其它狀態管理方案,因為它簡化了狀態管理,使代碼更清晰、更易讀,並與React的聲明性本質一致。 1)useState允許在函數組件中直接聲明狀態變量,2)它通過鉤子機制在重新渲染間記住狀態,3)使用useState可以利用React的優化如備忘錄化,提升性能,4)但需注意只能在組件頂層或自定義鉤子中調用,避免在循環、條件或嵌套函數中使用。

何時使用usestate()以及何時考慮替代狀態管理解決方案何時使用usestate()以及何時考慮替代狀態管理解決方案Apr 24, 2025 pm 04:49 PM

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

React的可重複使用的組件:增強代碼可維護性和效率React的可重複使用的組件:增強代碼可維護性和效率Apr 24, 2025 pm 04:45 PM

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionActActRossDifferentPartSofanApplicationorprojects.1)heSredunceRedUndenceNandSimplifyUpdates.2)yensureconsistencyInuserexperience.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1

記事本++7.3.1

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