最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

React State與生命周期詳細(xì)介紹

 更新時(shí)間:2022年08月31日 15:52:40   作者:小綿楊Yancy  
React將組件(component)看成一個(gè)狀態(tài)機(jī)(State Machines),通過其內(nèi)部自定義的狀態(tài)(State)和生命周期(Lifecycle)實(shí)現(xiàn)并與用戶交互,維持組件的不同狀態(tài)

一、State

在React當(dāng)中,當(dāng)你更新組件的state,然后新的state就會(huì)重新渲染到頁面中。在這個(gè)時(shí)候不需要你操作任何DOM。這和vue中組件的data中的數(shù)據(jù)是相似的。

1.1 類組件中的State

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>State</title>
    <script src="https://cdn.staticfile.org/react/16.8.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.8.0/umd/react-dom.development.js"></script>
    <!-- 生產(chǎn)環(huán)境中不建議使用 -->
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      class Clock extends React.Component {
        constructor(props) {
          super(props);
          this.state = { title: "React State", date: new Date() };
          this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
          this.setState({ date: new Date() });
        }
        render() {
          return (
            <div>
              <p>{this.state.title}</p>
              <p>現(xiàn)在是 {this.state.date.toLocaleTimeString()}.</p>
              <button onClick={this.handleClick}>更新時(shí)間</button>
            </div>
          );
        }
      }
      ReactDOM.render(<Clock />, document.getElementById("app"));
    </script>
  </body>
</html>

類組件需要在constructor中定義this.state對(duì)象,其對(duì)應(yīng)的屬性就是需要使用的state,例如上面代碼中的title和date屬性,在render函數(shù)中通過this.sate.XXX調(diào)用。

注意,修改state需要調(diào)用this.setState方法,不可以直接對(duì)state進(jìn)行賦值。

這里的handleClick是按鈕的點(diǎn)擊事件,點(diǎn)擊按鈕后,調(diào)用setState方法重新為date賦值,此時(shí)頁面會(huì)自動(dòng)更新。

1.2 函數(shù)組件中的State

函數(shù)組件沒有state => React v16.8.0推出Hooks API,其中的一個(gè)API叫做useState可以解決問題。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>State</title>
    <script src="https://cdn.staticfile.org/react/16.8.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.8.0/umd/react-dom.development.js"></script>
    <!-- 生產(chǎn)環(huán)境中不建議使用 -->
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      const Clock = (props) => {
        const [n, setN] = React.useState(0);
        function addNum() {
          setN(n + 1);
        }
        return (
          <div>
            <p>現(xiàn)在的n是 {n} .</p>
            <button onClick={addNum}>n+1</button>
          </div>
        );
      };
      ReactDOM.render(<Clock />, document.getElementById("app"));
    </script>
  </body>
</html>

可以看到,在函數(shù)組件中使用state需要借助useState,并且useState會(huì)返回setXXX方法用于修改定義的state,相比于類組件,函數(shù)組件更加簡潔,而且不用關(guān)注修改state時(shí)的this指向問題。

二、React生命周期

組件的生命周期可分成三個(gè)狀態(tài):

  • Mounting(掛載):已插入真實(shí) DOM
  • Updating(更新):正在被重新渲染
  • Unmounting(卸載):已移出真實(shí) DOM

2.1 掛載

當(dāng)組件實(shí)例被創(chuàng)建并插入 DOM 中時(shí),其生命周期調(diào)用順序如下:

  1. constructor(): 在 React 組件掛載之前,會(huì)調(diào)用它的構(gòu)造函數(shù)。
  2. getDerivedStateFromProps():在調(diào)用 render 方法之前調(diào)用,并且在初始掛載及后續(xù)更新時(shí)都會(huì)被調(diào)用。
  3. render(): render() 方法是 class組件中唯一必須實(shí)現(xiàn)的方法。
  4. componentDidMount(): 在組件掛載后(插入 DOM 樹中)立即調(diào)用。

render() 方法是 class 組件中唯一必須實(shí)現(xiàn)的方法,其他方法可以根據(jù)自己的需要來實(shí)現(xiàn)。

2.2 更新

每當(dāng)組件的 state 或 props 發(fā)生變化時(shí),組件就會(huì)更新。

當(dāng)組件的 props 或 state 發(fā)生變化時(shí)會(huì)觸發(fā)更新。組件更新的生命周期調(diào)用順序如下:

  1. getDerivedStateFromProps(): 在調(diào)用 render 方法之前調(diào)用,并且在初始掛載及后續(xù)更新時(shí)都會(huì)被調(diào)用。根據(jù)shouldComponentUpdate() 的返回值,判斷 React 組件的輸出是否受當(dāng)前 state 或 props更改的影響。
  2. shouldComponentUpdate():當(dāng) props 或 state 發(fā)生變化時(shí),shouldComponentUpdate() 會(huì)在渲染執(zhí)行之前被調(diào)用。
  3. render(): render() 方法是 class 組件中唯一必須實(shí)現(xiàn)的方法。
  4. getSnapshotBeforeUpdate(): 在最近一次渲染輸出(提交到 DOM節(jié)點(diǎn))之前調(diào)用。
  5. componentDidUpdate(): 在更新后會(huì)被立即調(diào)用。

render() 方法是 class 組件中唯一必須實(shí)現(xiàn)的方法,其他方法可以根據(jù)自己的需要來實(shí)現(xiàn)。

2.3 卸載

當(dāng)組件從 DOM 中移除時(shí)會(huì)調(diào)用如下方法:

componentWillUnmount(): 在組件卸載及銷毀之前直接調(diào)用。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Lifecycle</title>
    <script src="https://cdn.staticfile.org/react/16.8.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.8.0/umd/react-dom.development.js"></script>
    <!-- 生產(chǎn)環(huán)境中不建議使用 -->
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      class Button extends React.Component {
        constructor(props) {
          super(props);
          this.state = { data: 0 };
          this.setNewNumber = this.setNewNumber.bind(this);
        }
        setNewNumber() {
          this.setState({ data: this.state.data + 1 });
        }
        render() {
          return (
            <div>
              <button onClick={this.setNewNumber}>INCREMENT</button>
              <Content myNumber={this.state.data}></Content>
            </div>
          );
        }
      }
      class Content extends React.Component {
        componentWillMount() {
          console.log("Component WILL MOUNT!");
        }
        componentDidMount() {
          console.log("Component DID MOUNT!");
        }
        componentWillReceiveProps(newProps) {
          console.log("Component WILL RECEIVE PROPS!");
        }
        shouldComponentUpdate(newProps, newState) {
          return true;
        }
        componentWillUpdate(nextProps, nextState) {
          console.log("Component WILL UPDATE!");
        }
        componentDidUpdate(prevProps, prevState) {
          console.log("Component DID UPDATE!");
        }
        componentWillUnmount() {
          console.log("Component WILL UNMOUNT!");
        }
        render() {
          return (
            <div>
              <h3>{this.props.myNumber}</h3>
            </div>
          );
        }
      }
      ReactDOM.render(
        <div>
          <Button />
        </div>,
        document.getElementById("app")
      );
    </script>
  </body>
</html>

注意:只有類組件才有生命周期。函數(shù)組件每次都是重新運(yùn)行函數(shù),舊的組件即刻被銷毀。

2.4 函數(shù)式組件useEffect

與使用state需要借助useState一樣,在函數(shù)組件中,我們需要借助可以借助react提供的方法在函數(shù)式組件中實(shí)現(xiàn)“生命周期”,它就是useEffect

useEffect 給函數(shù)組件增加了操作副作用的能力。它跟 class 組件中的

componentDidMount、componentDidUpdate 和 componentWillUnmount 具有相同的用途,只不過被合并成了一個(gè) API。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>useEffect</title>
    <script src="https://cdn.staticfile.org/react/16.8.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.8.0/umd/react-dom.development.js"></script>
    <!-- 生產(chǎn)環(huán)境中不建議使用 -->
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      const Clock = (props) => {
        const [n, setN] = React.useState(0);
        function addNum() {
          setN(n + 1);
        }
        React.useEffect(() => {
          console.log(n);
        });
        return (
          <div>
            <p>現(xiàn)在的n是 {n} .</p>
            <button onClick={addNum}>n+1</button>
          </div>
        );
      };
      ReactDOM.render(<Clock />, document.getElementById("app"));
    </script>
  </body>
</html>

可以看到,上面的使用useEffect時(shí),掛載或者銷毀時(shí),都會(huì)觸發(fā)useEffect中的函數(shù),那么如何使用useEffect模擬生命周期呢?

//    只在組件掛載后顯示,只需要加個(gè)空數(shù)組做參數(shù)即可
    useEffect(() => {
        document.title = `You clicked ${count} times`;
    },[]);
//    銷毀階段
    useEffect(() => {
        return ()=>{
				console.log("銷毀階段")
			}
    });

三、總結(jié)

可以看到,類組件和函數(shù)組件在State和生命周期上區(qū)別還是非常大的,函數(shù)式組件需要調(diào)用react提供的hooks(鉤子函數(shù),非常重要,后面會(huì)專門學(xué)習(xí))來實(shí)現(xiàn)類組件對(duì)于的功能。

學(xué)習(xí)過程中,我發(fā)現(xiàn)react類組件類似于vue2的選項(xiàng)式api組件,而函數(shù)組件則vue3組合式api十分相似。

到此這篇關(guān)于React State與生命周期詳細(xì)介紹的文章就介紹到這了,更多相關(guān)React State內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • React中傳遞組件的三種方式小結(jié)

    React中傳遞組件的三種方式小結(jié)

    通過傳遞組件,我們可以將復(fù)雜組件內(nèi)部的一部分 UI 交由外部組件來控制渲染,這也是控制反轉(zhuǎn)(Inversion of Control)的一種體現(xiàn),在 React 中,我們可以通過三種方式來傳遞組件,本文就來給大家述說這三種方式,需要的朋友可以參考下
    2023-07-07
  • 教你應(yīng)用?SOLID?原則整理?React?代碼之單一原則

    教你應(yīng)用?SOLID?原則整理?React?代碼之單一原則

    這篇文章主要介紹了如何應(yīng)用?SOLID?原則整理?React?代碼之單一原則,今天,我們將從一個(gè)糟糕的代碼示例開始,應(yīng)用 SOLID 的第一個(gè)原則,看看它如何幫助我們編寫小巧、漂亮、干凈的并明確責(zé)任的 React 組件,需要的朋友可以參考下
    2022-07-07
  • ReactQuery系列之?dāng)?shù)據(jù)轉(zhuǎn)換示例詳解

    ReactQuery系列之?dāng)?shù)據(jù)轉(zhuǎn)換示例詳解

    這篇文章主要為大家介紹了ReactQuery系列之?dāng)?shù)據(jù)轉(zhuǎn)換示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • React實(shí)現(xiàn)組件間通信的幾種方式小結(jié)

    React實(shí)現(xiàn)組件間通信的幾種方式小結(jié)

    在React應(yīng)用中,組件間的通信是一個(gè)基礎(chǔ)而關(guān)鍵的概念,理解和掌握不同組件之間的通信方式,可以幫助我們構(gòu)建出更加模塊化、可維護(hù)和可擴(kuò)展的應(yīng)用程序,React提供了多種組件通信的方法,本文給大家詳細(xì)的介紹了這些方法,需要的朋友可以參考下
    2024-07-07
  • react實(shí)現(xiàn)記錄拖動(dòng)排序

    react實(shí)現(xiàn)記錄拖動(dòng)排序

    這篇文章主要介紹了react實(shí)現(xiàn)記錄拖動(dòng)排序的相關(guān)資料,需要的朋友可以參考下
    2023-07-07
  • React路由中的redux和redux知識(shí)點(diǎn)拓展

    React路由中的redux和redux知識(shí)點(diǎn)拓展

    這篇文章主要介紹了React路由中的redux和redux知識(shí)點(diǎn)拓展,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的朋友可以參考學(xué)習(xí)一下
    2022-08-08
  • React Native中Mobx的使用方法詳解

    React Native中Mobx的使用方法詳解

    這篇文章主要給大家介紹了關(guān)于React Native中Mobx的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法

    ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法

    這篇文章主要為大家介紹了ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • react 項(xiàng)目中引入圖片的幾種方式

    react 項(xiàng)目中引入圖片的幾種方式

    本文主要介紹了react 項(xiàng)目中引入圖片,本文詳細(xì)的介紹了幾種方法,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-06-06
  • 淺談react+es6+webpack的基礎(chǔ)配置

    淺談react+es6+webpack的基礎(chǔ)配置

    下面小編就為大家?guī)硪黄獪\談react+es6+webpack的基礎(chǔ)配置。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08

最新評(píng)論

敖汉旗| 抚州市| 海宁市| 南投县| 托里县| 合川市| 昌邑市| 棋牌| 凤阳县| 武夷山市| 邹城市| 株洲县| 平阴县| 邢台市| 开平市| 石柱| 荆门市| 贺兰县| 梨树县| 阿克陶县| 巴中市| 鄂伦春自治旗| 廊坊市| 凯里市| 石家庄市| 枣阳市| 长垣县| 八宿县| 霍林郭勒市| 英吉沙县| 延津县| 莱阳市| 乐清市| 宝应县| 富顺县| 河池市| 天柱县| 浦县| 柘城县| 高碑店市| 沧州市|