react生命周期-渲染階段


import React, { Component } from "react";

export default class Shengming extends Component {
  // 調用父類的 constructor方法;傳遞props屬性,染發props屬性起作用
  constructor(props) {
    super(props);

    // 定義初始值
    this.state = {
      num: 20,
    };
    console.log("1-1我是掛載階段的第一個生命周期函數");
  }
  //   UNSAFE
  componentWillMount() {
    console.log("1-2掛載數據之前");
  }

  componentDidMount() {
    //   用來發送請求
    console.log("1-4數據已經掛載好了");
  }

  //   =======================更新階段
  UNSAFE_componentWillReceiveProps() {
    // 在更新props屬性的時候,會觸發這個屬性當你沒有props這個參數的時候,就不會觸發哈
    //有props的時候,就會觸發
    console.log("2-1-props 在接受props屬性之前,只有prps改變才會執行這個函數");
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 是否要跟新數據
    console.log("2-2-props 在接受props屬性之前", nextProps, nextState);
    // return true; //這里表示是否跟新;true表示跟新數據,然后執行render函數; false表示不跟新數據不會執行后續的函數
    // Shengming.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.
    // 返回未定義的值,而不是布爾值。確保返回true或false。

    // 那我們什么時候,return true;如果我們 的數據發生變化了,就return true;
    // 數據沒有發生改變,就return false
     
    return nextState.num == this.state.num
     
  }

  componentWillUpdate() {
    console.log("2--3跟新數據之前");
  }

  componentDidUpdate() {
    console.log("2--4跟新數據之后");
  }

  changeState() {
    console.log(1);
    this.setState({
      num: 30,
    });
  }
  
  static defaultProps = {
    bg: "pink",
    wi: "100px",
    he: "100px",
  };
   // ===================================第三階段
   componentWillUnmount() {
      console.log("3-1組件銷毀的時候執行");
        // 在最后一個生命周期中;執行事件的銷毀;或者銷毀某些值的引用;
        // 比如;你在這個組件中給document;注冊了一個事件;
        // 當這個組件都消失了,按理說這個事件就應該銷毀;
        // 但是如果你不做處理的話,那么這個事件在其他組件頁面仍然會被觸發哈;
   }

  render() {
    console.log("1-3render 標簽渲染到頁面");
    return (
      <div  style={{
          background: this.props.bg,
          width: this.props.wi,
          height: this.props.he,
        }}>
        123==》{this.state.num}
        <br />
        <button onClick={this.changeState.bind(this)}>按鈕</button>
      </div>
    );
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM