日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

react組件的生命周期

作者:二臉懵逼 更新時(shí)間: 2022-07-30 編程語言

react組件的生命周期

  • 1、什么是生命周期?
  • 2、生命周期流程圖(舊)
      • 2.1 、生命周期的三個(gè)階段(舊)
  • 3、生命周期流程圖(新)
      • 3.1、被棄用的三個(gè)鉤子函數(shù)
      • 3.2、生命周期的三個(gè)階段(新)

需求:定義組件實(shí)現(xiàn)以下功能:

  1. 讓指定的文本做顯示 / 隱藏的漸變動(dòng)畫
  2. 從完全可見,到徹底消失,耗時(shí)2S
  3. 點(diǎn)擊“不活了”按鈕從界面中卸載組件
 //1、創(chuàng)建組件
    class Demo extends React.Component {
        state = {opacity: 1}
        death = () => {
            //卸載組件
            ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }
        //組件完成掛載后執(zhí)行
        componentDidMount() {
            this.timer=setInterval(() => {
                //    獲取原狀態(tài)
                let {opacity} = this.state;
                //    減小0.1
                opacity -= 0.1
                if (opacity <= 0) opacity = 1
                this.setState({opacity})
            }, 200)
        }

        //組件將要卸載時(shí)調(diào)用
        componentWillUnmount(){
            //清除定時(shí)器
            clearInterval(this.timer)
        }
        //render調(diào)用時(shí)機(jī):初始化渲染、狀態(tài)更新之后
        render() {
            return (
                <div>
                    <h1 style={{opacity: this.state.opacity}}>react感覺還是有點(diǎn)難滴!!!怎么辦?</h1>
                    <button onClick={this.death}>不活了</button>
                </div>
            )
        }
    }

    //2、渲染虛擬DOM
    ReactDOM.render(<Demo/>, document.getElementById('test'))

1、什么是生命周期?

  1. 組件從創(chuàng)建到死亡它會(huì)經(jīng)歷一些特定的階段。
  2. React組件中包含一系列勾子函數(shù)(生命周期回調(diào)函數(shù)), 會(huì)在特定的時(shí)刻調(diào)用。
  3. 我們在定義組件時(shí),會(huì)在特定的生命周期回調(diào)函數(shù)中,做特定的工作

2、生命周期流程圖(舊)

在這里插入圖片描述

2.1 、生命周期的三個(gè)階段(舊)

  1. 初始化階段: 由ReactDOM.render()觸發(fā)—初次渲染
    1. constructor()
    2. componentWillMount()
    3. render()
    4. componentDidMount()---------常用,一般在這個(gè)鉤子函數(shù)做一些初始化操作,例如:開啟定時(shí)器,發(fā)起網(wǎng)絡(luò)請求,訂閱消息等等…
  2. 更新階段: 由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)
    1. shouldComponentUpdate()
    2. componentWillUpdate()
    3. render()--------必須使用的一個(gè)
    4. componentDidUpdate()
  3. 卸載組件: 由ReactDOM.unmountComponentAtNode()觸發(fā)
    1. componentWillUnmount()--------常用,一般在這個(gè)鉤子函數(shù)做一些收尾的事兒,例如:關(guān)閉定時(shí)器、取消定時(shí)器…
 //1、創(chuàng)建組件
    class Count extends React.Component {
        //構(gòu)造器
        constructor(props) {
            console.log('count-constructor');
            super(props);
            this.state = {count: 0}
        }

        //將要掛載
        componentWillMount() {
            console.log('count-componentWillMount');
        }

        //掛載后
        componentDidMount() {
            console.log('count-componentDidMount');
        }

        //將要卸載
        componentWillUnmount() {
            //清除定時(shí)器
            console.log('count-componentWillUnmount');
        }

        //控制組件是否更新的”閥門“
        shouldComponentUpdate() {
            console.log('count-shouldComponentUpdate');
            return true;//返回false狀態(tài)無法更新,返回值為true,則更新
        }

        //組件將要更新
        componentWillUpdate() {
            console.log('count-componentWillUpdate');
        }

        //組件更新完成
        componentDidUpdate() {
            console.log('count-componentDidUpdate');
        }

        //count+1
        add = () => {
            //    獲取原狀態(tài)
            let {count} = this.state;
            this.setState({
                count: count + 1
            })
        }
        //卸載組件
        unmount = () => {
            ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }
        //強(qiáng)制更新
        force = () => {
            //強(qiáng)制更新(無  控制組件是否更新的‘閥門’的步驟)
            this.forceUpdate();
        }

        render() {
            console.log('count-render');
            let {count} = this.state;
            return (
                <div>
                    <h1>當(dāng)前求和為:{count}</h1>
                    <button onClick={this.add}>點(diǎn)擊+1</button>
                    <button onClick={this.unmount}>卸載組件</button>
                    <button onClick={this.force}>不更改任何狀態(tài)中的數(shù)據(jù),強(qiáng)制更新一下</button>
                </div>
            )
        }
    }

    //父組件
    class Father extends React.Component {
        state = {carName: '寶馬'}
        changeCar = () => {
            this.setState({
                carName: '馬自達(dá)'
            })
        }

        render() {
            return (<div>
                    <div>Father</div>
                    <button onClick={this.changeCar}>換車</button>
                    <Child carName={this.state.carName}></Child>
                </div>
            )
        }
    }

    //子組件
    class Child extends React.Component {
        //組件將要接收父組件傳過來的新的屬性值(第一次不會(huì)執(zhí)行)
        componentWillReceiveProps(props) {
            console.log('Child-componentWillReceiveProps',props);
        }

        render() {
            return (<div>我是Child組件,我從Father組件中接收到的車是:{this.props.carName}</div>)
        }
    }

    //2、渲染虛擬DOM
    // ReactDOM.render(<Count/>, document.getElementById('test'))
    ReactDOM.render(<Father/>, document.getElementById('test'))

3、生命周期流程圖(新)

在這里插入圖片描述

3.1、被棄用的三個(gè)鉤子函數(shù)

    1. componentWillMount
    1. componentWillReceiveProps
    1. componentWillUpdate

??現(xiàn)在使用會(huì)出現(xiàn)警告,需要加上UNSAFE_前綴才能使用,以后可能會(huì)被徹底廢棄,不建議使用。

3.2、生命周期的三個(gè)階段(新)

  1. 初始化階段: 由ReactDOM.render()觸發(fā)—初次渲染
    1. constructor()
    2. getDerivedStateFromProps
    3. render()
    4. componentDidMount()---------常用,一般在這個(gè)鉤子函數(shù)做一些初始化操作,例如:開啟定時(shí)器,發(fā)起網(wǎng)絡(luò)請求,訂閱消息等等…
  2. 更新階段: 由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)
    1. getDerivedStateFromProps
    2. shouldComponentUpdate()
    3. render()
    4. getSnapshotBeforeUpdate
    5. componentDidUpdate()
  3. 卸載組件: 由ReactDOM.unmountComponentAtNode()觸發(fā)
    1. componentWillUnmount()--------常用,一般在這個(gè)鉤子函數(shù)做一些收尾的事兒,例如:關(guān)閉定時(shí)器、取消定時(shí)器…
    //1、創(chuàng)建組件
    class Count extends React.Component {
        //構(gòu)造器
        constructor(props) {
            console.log('count-constructor');
            super(props);
            this.state = {count: 0}
        }

        // 若state的值在任何時(shí)候都取決于props,可以使用
        //派生狀態(tài)(state的值在任何時(shí)候都取決于props.派生狀態(tài)會(huì)導(dǎo)致代碼冗余,并使組件難以維護(hù))
        static getDerivedStateFromProps(props, state) {
            //必須有返回值,null或state obj狀態(tài)對(duì)象
            console.log('count-getDerivedStateFromProps', props, state);
            return null;
            // return props;//返回狀態(tài)對(duì)象會(huì)影響狀態(tài)的更新
        }

        getSnapshotBeforeUpdate(prevProps, prevState) {
            console.log('count-getSnapshotBeforeUpdate', prevProps, prevState);
            return 'xiao';
        }
        //掛載后
        componentDidMount() {
            console.log('count-componentDidMount');
        }

        //將要卸載
        componentWillUnmount() {
            //清除定時(shí)器
            console.log('count-componentWillUnmount');
        }

        //控制組件是否更新的”閥門“
        shouldComponentUpdate() {
            console.log('count-shouldComponentUpdate');
            return true;//返回false狀態(tài)無法更新,返回值為true,則更新
        }

        //組件更新完成(第三個(gè)參數(shù)為getSnapshotBeforeUpdate鉤子函數(shù)的返回值)
        componentDidUpdate(prevProps, prevState,snapshotValue) {
            console.log('count-componentDidUpdate',prevProps, prevState,snapshotValue);
        }

        //count+1
        add = () => {
            //    獲取原狀態(tài)
            let {count} = this.state;
            this.setState({
                count: count + 1
            })
        }
        //卸載組件
        unmount = () => {
            ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }

        render() {
            console.log('count-render');
            let {count} = this.state;
            return (
                <div>
                    <h1>當(dāng)前求和為:{count}</h1>
                    <button onClick={this.add}>點(diǎn)擊+1</button>
                    <button onClick={this.unmount}>卸載組件</button>
                </div>
            )
        }
    }

    //2、渲染虛擬DOM
    ReactDOM.render(<Count count="99"/>, document.getElementById('test'))

getSnapshotBeforeUpdate的應(yīng)用場景:

??以特殊方式處理滾動(dòng)位置

 //1、創(chuàng)建組件
    class NewsList extends React.Component {
        state = {newsArr: []}

        componentDidMount() {
            setInterval(() => {
                //    獲取原來的狀態(tài)值
                const {newsArr} = this.state;
                //    模擬一條新聞
                const news = '新聞' + (newsArr.length + 1);
                //    更新狀態(tài)
                this.setState({
                    newsArr: [news, ...newsArr]
                })
            }, 1000)
        }

        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight
        }

        componentDidUpdate(prevProps, prevState, snapshotValue) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshotValue;
        }

        render() {
            return (
                <div className="list" ref="list">
                    {this.state.newsArr.map((item, index) => {
                        return <div className="news" key={index}>{item}</div>
                    })}
                </div>
            )
        }
    }

    ReactDOM.render(<NewsList/>, document.getElementById('test'))

原文鏈接:https://blog.csdn.net/fangqi20170515/article/details/126052535

欄目分類
最近更新