四、React的组件化开发-组件常用生命周期

70 阅读1分钟

组件分类

类组件

class App extends React.Component {
   constructor() {
     super()
   }
   render() {
     return (
       <div>
         <h2>类组件</h2>
       </div>
     )
   }
}

函数式组件

function App() {
    return (
        <div>
             <h2>函数组件</h2>
       </div>
    )
}
  • 暂不考虑hooks
  • 类组件与函数组件返回值
  • 函数组件没有自己的生命周期
  • 函数组件里面不使用this
  • 函数式组件没有内部状态

组件的生命周期

  • 执行constructor的构造方法

  • 执行render方法

  • componentDidMount组件完成渲染

  • 组件发生更新会重新执行render函数

import React from "react";
// 1. 类组件的生命周期
class App extends React.Component {
  // 1.1 挂载Mounting阶段-执行构造方法constructor实例
  constructor() {
    console.log("constructor第一步");
    super();

    this.state = {
      msg: "信息",
    };
  }

  btnClick() {
    this.setState({
      msg: "修改后的值",
    });
  }
  // 1.2 挂载Mounting阶段-执行render函数
  render() {
    console.log("render第二步");
    let { msg } = this.state;
    return (
      <div>
        <h2 onClick={() => this.btnClick()}>{msg}</h2>
      </div>
    );
  }

  // 1.3 组件被渲染到DOM上
  componentDidMount() {
    console.log("componentDidMount组件被渲染到DOM上第三步");
  }

  // 1.4 组件发生更新会重新执行 render函数
  componentDidUpdate() {
    console.log("组件发生了更新完成");
  }

  // 卸载阶段
  componentWillUnmount() {
    console.log("组件即将被卸载掉");
  }
}

export default App;