React的生命周期

DOM 生命周期

在談React的生命周期之前,先來看看原始寫法的生命周期是什么樣的

let app = document.getElementById("app");

// create div
let div = document.createElement("div");

let state = 0;
div.innerHTML = `
  <p>${state}</p>
  <button>+</button>
  <button>die</button>
`;

// mount div
app.appendChild(div);

div.style.border = "1px solid red";

div.querySelector("button").onclick = function() {
  state += 1;
  // update div
  div.querySelector("p").innerText = state;
};

div.querySelectorAll("button")[1].onclick = function() {
  // 把所有引用都清除
  div.querySelector("button").onclick = null;
  div.querySelectorAll("button")[1].onclick = null;
  div.remove();
  div = null; 
  // destroy div
};

上面這段代碼描述了一個div的生命周期即創(chuàng)建銷毀過程,如果搞懂了這個那React的生命周期也同理。

React 生命周期圖解

React生命周期圖解

下面可以嘗試著用 React 的生命周期來寫一遍。但是需要注意的是:React 在 16.3版本以后,將一些生命周期方法列為了不安全的生命周期。至于為什么這些生命周期方法是不安全的,React 認(rèn)為這些生命周期方法經(jīng)常被誤解和巧妙地濫用,并且預(yù)計這種濫用可能會在異步渲染方面帶來問題。在 17.0 版本將刪除componentWillMount,componentWillReceivePropscomponentWillUpdate。(從這個版本開始開始,只有新的“UNSAFE_”生命周期名稱起作用。)

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

React 生命周期

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
    console.log("create");
  }
  onClick() {
    this.setState({
      count: this.state.count + 1
    });
  }
  UNSAFE_componentWillMount() {
    console.log("will mount");
  }
  componentDidMount() {
    console.log("did mount");
  }
  UNSAFE_componentWillUpdate() {
    console.log("will update");
  }
  componentDidUpdate() {
    console.log("did update");
  }
  render() {
    console.log("mount or update");
    return (
      <div className="App">
        {this.state.count}
        <button onClick={() => this.onClick()}>+</button>
      </div>
    );
  }
}

/*console.log依次打印出
create
will mount
mount or update
did mount
will update
mount or update
did update
*/

總結(jié)一下,constructor構(gòu)造函數(shù)是create的作用,組件掛載到DOM上之前會調(diào)用UNSAFE_componentWillMount鉤子,組件掛載調(diào)用render函數(shù),掛載完成調(diào)用componentDidMount鉤子,如果渲染的數(shù)據(jù)發(fā)生更新,也就是操作this.setState()的時候,在更新之前會調(diào)用UNSAFE_componentWillUpdate鉤子,組件更新時再調(diào)用一次render函數(shù),更新完成調(diào)用componentDidUpdate鉤子。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容