react生命周期(舊)

1.代碼

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function fetchData() {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('獲取ajax數(shù)據(jù)');
    }, 2000);
  });
}

class Welcome extends Component {
  constructor(props) {
    console.log("constructor", props);
    super(props);
    this.state = {
      color: props.color
    };
  }

  componentWillMount() {
    console.log("componentWillMount");
    // this.setState({color: "yellow"}); 1.在componentWillMount中setState

    // setTimeout(() => {                       /***************************************************/
    //   this.setState({ color: "green" });     /******2.在componentWillMount中延時(shí)setState**********/
    // }, 1000);                                /***************************************************/
  }

  componentDidMount() {
    console.log("componentDidMount");
   // this.setState({ color: "yellow" }); 3.在componentDidMount中setState
  }

  componentWillReceiveProps(nextProps, nextState) {
    console.log("componentWillReceiveProps", nextProps, nextState);
    if (nextProps.color !== this.state.color) {
      this.setState({ color: nextProps.color });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    return true;
  }

  componentWillUpdate(nextProps, nextState) {
    console.log("componentWillUpdate", nextProps, nextState);
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("componentDidUpdate", prevProps, prevState);
  }

  changeColor = () => {
    this.setState({color: "#ddd"})
  }
  render() {
    console.log("render", this.state.color);
    return (
      <div style={{ background: this.state.color }}>
        <h1>react 舊的生命周期</h1>
        <p>{this.state.color}</p>
        <button onClick={this.changeColor}>內(nèi)部change color</button>
      </div>
    );
  }
}

class App extends Component {
  state = {
    currentColor: "red",
    colorIndex: 0
  };

  changeColor = () => {
    let colors = ["red", "yellow", "blue", "green", "pink"];
    let { colorIndex } = this.state;
    colorIndex = ++colorIndex % 5;
    this.setState({
      currentColor: colors[colorIndex],
      colorIndex
    });
  };

  render() {
    let { currentColor } = this.state;
    return (
      <div className="App">
        <Welcome color={currentColor} />
        <hr />
        <button onClick={this.changeColor}>外部change color</button>
      </div>
    );
  }
}

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

2. 輸出結(jié)果

1.直接輸出
constructor {color: "red"}
componentWillMount
render red
componentDidMount
2.componentWillMount中改變state
  • 在componentWillMount中改變state,即將代碼注釋1處打開,setState先執(zhí)行,改變完了state,然后才執(zhí)行render,可見在這方法里同步地設(shè)置狀態(tài)將不會(huì)觸發(fā)重渲。
constructor {color: "red"}
componentWillMount
render yellow
componentDidMount
  • 在componentWillMount中延時(shí)改變state,即將代碼注釋2處打開, 因?yàn)檠訒r(shí),render在setState之前執(zhí)行,執(zhí)行完了,會(huì)觸發(fā)一次重新渲染(render)??梢娫谶@方法里異步地設(shè)置狀態(tài)會(huì)觸發(fā)重渲。
constructor {color: "red"}
componentWillMount
render red
componentDidMount
shouldComponentUpdate {color: "red"} {color: "green"}
componentWillUpdate {color: "red"} {color: "green"}
render green
componentDidUpdate {color: "red"} {color: "red"}
  • 在componentWillMount中使用async,await(發(fā)送ajax),將componentWillMount改成如下形式
  async componentWillMount() {
    console.log("componentWillMount");
    let result = await delay()
    this.setState({ color: "green" });
  }

輸出結(jié)果如下,也會(huì)觸發(fā)一次重新渲染(render),what the Fuck?。。?/strong>
我一直以為不會(huì)重新渲染,那為什么ajax請(qǐng)求不建議放在componentWillMount中,網(wǎng)上搜了一大堆,都說不能觸發(fā)重新render,莫不是智障?????

constructor {color: "red"}
componentWillMount
render red
componentDidMount
result 獲取ajax數(shù)據(jù)
shouldComponentUpdate {color: "red"} {color: "green"}
componentWillUpdate {color: "red"} {color: "green"}
render green
componentDidUpdate {color: "red"} {color: "red"}
3.componentDidMount中改變state
  • 在componentDidMount中改變state,即將代碼注釋3處打開,可見componentDidMount會(huì)重新觸發(fā)一次render,注意這里沒有ajax的異步請(qǐng)求,直接setState就會(huì)重新渲染?。?!
constructor {color: "red"}
componentWillMount
render red
componentDidMount
shouldComponentUpdate {color: "red"} {color: "yellow"}
componentWillUpdate {color: "red"} {color: "yellow"}
render yellow
componentDidUpdate {color: "red"} {color: "red"}
4.改變父組件傳入值,從而改變子組件state

點(diǎn)擊父組件改變顏色按鈕,改變父組件傳入的props的值,查看結(jié)果
componentWillReceiveProps => shouldComponentUpdate => componentWillUpdate => render => componentDidUpdate

componentWillReceiveProps {color: "yellow"} {}
shouldComponentUpdate {color: "yellow"} {color: "yellow"}
componentWillUpdate {color: "yellow"} {color: "yellow"}
render yellow
componentDidUpdate {color: "red"} {color: "yellow"}
5.改變子組件state值

點(diǎn)擊子組件改變顏色按鈕,改變子組件state值,查看結(jié)果
shouldComponentUpdate => componentWillUpdate => render => componentDidUpdate

shouldComponentUpdate {color: "red"} {color: "#ddd"}
componentWillUpdate {color: "red"} {color: "#ddd"}
render #ddd
componentDidUpdate {color: "red"} {color: "yellow"}

實(shí)例網(wǎng)站

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

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

  • 作為一個(gè)合格的開發(fā)者,不要只滿足于編寫了可以運(yùn)行的代碼。而要了解代碼背后的工作原理;不要只滿足于自己的程序...
    六個(gè)周閱讀 8,686評(píng)論 1 33
  • 前言 為了進(jìn)一步的了解React的工作過程,已經(jīng)曉得了怎么編寫React組件,知道了React的數(shù)據(jù)流,那么是時(shí)候...
    itclanCoder閱讀 937評(píng)論 0 1
  • 生命周期流程圖簡(jiǎn)單如下: 組件讓你把用戶界面分成獨(dú)立的,可重復(fù)使用的部分,并且將每個(gè)部分分開考慮。React.Co...
    Simple_Learn閱讀 1,197評(píng)論 0 0
  • 1. 內(nèi)容一 首先我使用class組件實(shí)現(xiàn)一個(gè)簡(jiǎn)單的界面: 以上代碼沒有任何疑點(diǎn),都是之前的博客當(dāng)中常見的語法 2...
    Qingelin閱讀 591評(píng)論 0 1
  • 午夜結(jié)束了喧囂,以一陣?guó)B鳴拉開帷幕。 緩緩升起的朝陽,宣示著新的一天來臨。 我現(xiàn)在窗前,現(xiàn)在是2023年,我突然想...
    楠芮閱讀 784評(píng)論 8 2

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