Next 的原理分析_React原理(生命周期)

159 阅读2分钟

生命周期是前端开发常见的知识点,也是一种钩子函数; 官方说明

挂载阶段

  • constructor()

初始化阶段,this绑定,state 初始化;

-componentwillmount

组件渲染之前,Dom渲染之前,render 之前,且只会调一次,使用次数不多;16.3 过期,getDerivedStateFromProps 替代

  • render()

唯一必要方法,进行ui渲染描述,返回react元素,只是渲染描述,并不会真的渲染,是一个纯函数,不能执行任何操作,防止数据循环,主要作用返回props/state 对应的结果,讲jsx 文件的组件转化为虚拟DOM

  • componentDidMount()

ui真正的ui渲染,DOM 渲染,获取真实DOM,只会调用一次,一般进行数据请求和第三方初始化;

更新阶段

  • componentwillreceiveprops

props 更新的时候触发,state 变更并不会更新,父组件的render()发生改变也会跟着改变,也是快过期,官方推荐使用:getDerivedStateFromProps(props, state)

  • shouldComponentUpdate

是否通知组件ui更新,决定组件是否重新渲染。返回 true 表示重新渲染,返回 false 表示不重新渲染。不能调用setState 防止循环ui渲染,因为State状态的改变会导致此方法的执行

  • shouldComponentDidupdate

更新完调用,可以操作dom

卸载阶段

  • componentWillUnmount

组件卸载前调用。可以在这里进行清理操作,例如移除事件监听器或取消网络请求。

示例代码

函数组件

import React, { useState, useEffect } from 'react';

function ExampleComponent() {
  const [count, setCount] = useState(0);

  // 模拟 componentDidMount 和 componentDidUpdate
  useEffect(() => {
    // 组件挂载或更新时执行的代码
    console.log(`You clicked ${count} times`);

    // 模拟 componentWillUnmount
    return () => {
      // 组件卸载时执行的代码
      console.log('Component will unmount');
    };
  }, [count]); // 依赖数组,只有 count 变化时才会重新执行

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default ExampleComponent;

类组件

import React from 'react';

class LifecycleDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('Constructor: 初始化状态和绑定事件处理程序');
  }

  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps: 从 props 派生状态');
    return null; // 返回 null 表示状态不需要更新
  }

  componentDidMount() {
    console.log('componentDidMount: 组件挂载后');
    // 可以在这里进行 DOM 操作或数据获取
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate: 决定组件是否重新渲染');
    return true; // 返回 true 表示重新渲染,返回 false 表示不重新渲染
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate: 捕获更新前的信息');
    return null; // 返回值将作为 componentDidUpdate 的第三个参数
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate: 组件更新后');
    // 可以在这里进行 DOM 操作或数据获取
  }

  componentWillUnmount() {
    console.log('componentWillUnmount: 组件卸载前');
    // 可以在这里进行清理操作,例如移除事件监听器或取消网络请求
  }

  render() {
    console.log('render: 渲染组件的 UI');
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

export default LifecycleDemo;