React的生命周期

中文文檔:State&生命周期-React
英文文檔:StateandLifecycle–React

簡單來說,一個(gè)組件的生命周期可以分為四個(gè)部分:

  1. 創(chuàng)造 - 生
  2. 掛載到頁面
  3. 更新
  4. 毀滅 - 死

用js來寫個(gè)簡單的例子

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

//create div
let div = document.createElement('div');
div.style.border = '1px solid red';

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

//mount div
app.appendChild(div);

div.querySelector('button').onClick = () => {
    state += 1;
    //update div
    div.querySelector('p').innerText = state;
};

div.querySelectorAll('button')[1].onClick = () => {
    //清理事件監(jiān)聽
    div.querySelector('button').onClick = null;
    div.querySelectorAll('button')[1].onClick = null;
    div.remove();
    //destroy div
    div = null;  
};

再來看看React的生命周期



值得注意的是,函數(shù)是沒有生命周期的,只有class組件有

來看看React的生命周期里有哪些鉤子

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

let div = document.createElement("div");
document.body.appendChild(div);
console.log = function(content) {
  div.innerHTML += `${content}<br>`;
};

class Baba extends React.Component {
  constructor() {
    super();
    this.state = {
      hasChild: true
    };
  }
  onClick() {
    this.setState({
      hasChild: false
    });
  }
  callSon() {
    this.setState({
      word: "你還好吧"
    });
  }
  render() {
    return (
      <div>
        我是你爸爸
        <button onClick={() => this.onClick()}>kill son</button>
        <button onClick={() => this.callSon()}>call son</button>
        {this.state.hasChild ? <App word={this.state.word} /> : null}
      </div>
    );
  }
}

class App extends React.Component {
  onClick() {
    console.log("用戶點(diǎn)擊了");
    this.setState({
      n: this.state.n + 1
    });
  }
  updateX() {
    this.setState({
      x: this.state.x + "!"
    });
  }
  constructor() {
    super();
    this.state = {
      n: 0,
      x: "不展示"
    };
  }
  componentWillMount() {
    console.log("將要 mount App");
  }
  render() {
    // update
    console.log("填充/更新 App 的內(nèi)容");
    return (
      <div className="App">
        {this.state.n}
        <br />
        我爸說 {this.props.word}
        <br />
        <button onClick={() => this.onClick()}>+1</button>
        <button onClick={() => this.updateX()}>update x</button>
      </div>
    );
  }
  componentDidMount() {
    console.log("mount App 完畢");
  }
  componentWillUpdate() {
    console.log("update App 之前");
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log("要不要更新呢?");
    if (this.state.n === nextState.n) {
      console.log('不更新')
      return false;
    } else {
      console.log('更新')
      return true;
    }
  }
  //update is render
  componentDidUpdate() {
    console.log("update App 之后");
  }
  componentWillUnmount() {
    console.log("App 快要死了,記得喂狗");
  }
  componentWillReceiveProps() {
    console.log("我爸說話了");
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Baba />, rootElement);

關(guān)于React生命周期的幾道面試題

生命周期的哪個(gè)階段異步請求數(shù)據(jù)?

componentDidMount
最主要的原因是:

  1. 在componentWillUnMount中無法確保在執(zhí)行render前已經(jīng)獲得了異步請求的數(shù)據(jù),componentDidMount不存在這個(gè)問題;
  2. 為了性能的需要,React下一代tiao'he
  3. 無法保證ajax請求在組件的更新階段里成功返回?cái)?shù)據(jù),有可能當(dāng)我們進(jìn)行setState處理的時(shí)候,組件已經(jīng)被銷毀了。

請說出所有的生命周期鉤子

  1. constructor()
  2. componentWillMount() // 將要Mount
  3. render() // 填充/更新
  4. componentDidMount() // Mount 完畢
  5. componentWillUpdate // 更新之前
  6. componentDidUpdate // 更新之后
  7. componentWillUnmount() // 組件被銷毀之前,只能由父組件銷毀子組件
  8. componentWillReceiveProps() // 父組件向子組件傳值了
  9. shouldComponentUpdate() //是否要更新
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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