React 学习(一) 生命周期

Lifecycles[^lifecycles]

图例

  • getDerivedStateFromProps: Keeping the props always is the same as New props

  • shouldComponentUpdate: We can control the components which should be re rendered

  • getSnapshotBeforeUpdate: The snapshot before update

// Life cycle is for class components, and function components are simulated by hooks
import React, { Component } from "react";

class Cpn extends Component {
  render() {
    return (
      <div>
        <h2>我是Cpn组件</h2>
      </div>
    );
  }

  componentWillUnmount() {
    console.log("componentWillUnmount called");
  }
}

export default class App extends Component {
  /**
   * 1.init state
   * 2.bind this pointer
   */
  constructor() {
    super();

    this.state = {
      count: 0,
      isShow: false,
    };

    console.log("constructor called");
  }

  render() {
    console.log("render called");
    return (
      <div>
        <span>App</span>
        <h2>Counter: {this.state.count}</h2>
        <button onClick={(e) => this.increment()}>+1</button>

        <hr />
        <button onClick={(e) => this.changeCpnShow()}>change</button>
        {this.state.isShow && <Cpn />}
      </div>
    );
  }

  changeCpnShow() {
    this.setState({
      isShow: !this.state.isShow,
    });
  }

  increment() {
    this.setState({
      count: this.state.count + 1,
    });
  }

  /**
   * 1.Operation dependent on DOM
   * 2.Send the network(Vue->created)
   * 3.add some subscribe(unsubscribe in componentWillUnmount)
   */
  componentDidMount() {
    console.log("componentDidMount called");
  }

  /**
   * 1.Be called after component updated
   * 2.Compare the props
   */
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate called");
  }
}

shouldComponentUpdate[^shouldComponentUpdate]

// Use the shouldComponentUpdate controls the render function
import React, { Component } from "react";

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      counter: 0,
      message: "Hello World",
    };
  }

  render() {
    console.log("App called");
    return (
      <div>
        <h2>counter: {this.state.counter}</h2>
        <h2>message: {this.state.message}</h2>
        <button
          onClick={(e) => {
            this.increment();
          }}
        >
          +
        </button>
        <button
          onClick={(e) => {
            this.changeText();
          }}
        >
          ChangeText
        </button>
      </div>
    );
  }

  // Determine whether the component is updated
  shouldComponentUpdate(nextProps, nextState) {
    // console.log("nextState", nextState);
    if (this.state.counter !== nextState.counter) return true;
    return false;
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1,
    });
  }

  changeText() {
    this.setState({
      message: "Small Stars",
    });
  }
}

posted @ 2020-11-26 17:15  北冥雪  阅读(90)  评论(0编辑  收藏  举报