1. 程式人生 > 實用技巧 >react生命週期-渲染階段

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這個引數的時候,就不會觸發哈
    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,
    });
  }

  render() {
    console.log("1-3render 標籤渲染到頁面");
    return (
      <div>
        123==》{this.state.num}
        <br />
        <button onClick={this.changeState.bind(this)}>按鈕</button>
      </div>
    );
  }
}