React生命周期案例详解

news/2024/10/8 7:35:13/

React 组件的生命周期是指组件从创建、渲染、更新到卸载的整个过程。在 React 16 及之前的版本中,生命周期方法被分为几个不同的阶段:挂载(Mounting)、更新(Updating)、卸载(Unmounting)以及错误处理(Error Handling,React 16 引入)。但从 React 17 开始,一些生命周期方法被标记为不推荐使用(如 componentWillMount、componentWillReceiveProps、componentWillUpdate),并引入了新的钩子函数 getDerivedStateFromProps 和 componentDidMount(实际上 componentDidMount 在更早的版本就已存在,但这里强调其作为替代某些旧生命周期方法的作用)。在 React 18 中,又引入了新的并发特性,这可能会进一步影响生命周期的概念,但本文主要基于 React 16.x 和 17.x 进行讲解。
挂载(Mounting)
这是组件被插入到 DOM 中的过程。
constructor(props)
类组件的构造函数,初始化 state 或绑定事件处理函数时调用。
jsx
   class MyComponent extends React.Component {
     constructor(props) {
       super(props);
       this.state = {
         count: 0
       };
     }
   }
   
static getDerivedStateFromProps(props, state)
当组件实例化后和接收新的 props 时将被调用。它应返回一个对象来更新 state,或者返回 null 来表明新的 props 不需要更新任何 state。
jsx
   class MyComponent extends React.Component {
     static getDerivedStateFromProps(props, state) {
       if (props.count !== state.count) {
         return { count: props.count };
       }
       return null;
     }
   }
   
render()
必须的方法,当组件需要更新时被调用,返回组件要渲染的内容。
jsx
   class MyComponent extends React.Component {
     render() {
       return <div>{this.state.count}</div>;
     }
   }
   
componentDidMount()
组件挂载到 DOM 之后调用。此时可以进行 API 调用、订阅等操作。
jsx
   class MyComponent extends React.Component {
     componentDidMount() {
       // 执行 API 调用等
     }
   }
   
更新(Updating)
组件的 props 或 state 发生变化时会进入更新过程。
static getDerivedStateFromProps(props, state)
组件更新时被调用,用于根据新的 props 来设置 state。
shouldComponentUpdate(nextProps, nextState)
决定组件是否应该更新。默认返回 true。返回 false 会阻止更新。
jsx
   class MyComponent extends React.Component {
     shouldComponentUpdate(nextProps, nextState) {
       if (nextProps.count === this.props.count) {
         return false;
       }
       return true;
     }
   }
   
render()
更新后,重新渲染组件。
getSnapshotBeforeUpdate(prevProps, prevState)
真实的 DOM 更新前调用。返回的值作为 componentDidUpdate 的第三个参数。
jsx
   class MyComponent extends React.Component {
     getSnapshotBeforeUpdate(prevProps, prevState) {
       // 例如,记录滚动位置等
       return null;
     }
   }
   
componentDidUpdate(prevProps, prevState, snapshot)
更新后立即调用。可以在这执行 DOM 操作或者执行更多的更新操作。
jsx
   class MyComponent extends React.Component {
     componentDidUpdate(prevProps, prevState, snapshot) {
       // 例如,处理 DOM 更新后的逻辑
     }
   }
   
卸载(Unmounting)
componentWillUnmount()
组件卸载和销毁之前调用。用于执行必要的清理操作,如取消网络请求、移除订阅等。
jsx
   class MyComponent extends React.Component {
     componentWillUnmount() {
       // 清理操作
     }
   }
   
错误处理(Error Handling)
React 16 引入了错误边界的概念,可用以下生命周期方法捕获子组件树的 JavaScript 错误。
static getDerivedStateFromError(error)
当子组件树中有组件抛出错误后,这个生命周期方法会被调用,返回值将作为 state。
componentDidCatch(error, info)
该生命周期方法会在后代组件抛出错误后被调用,可以用来记录错误信息。
错误边界组件示例:
jsx
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // 可以将错误日志上报给你的服务器
    console.log(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
使用错误边界:
jsx
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>
使用函数组件和 Hooks
在函数组件中,你可以使用 React Hooks 来模拟类组件中的生命周期方法。
useEffect 可以模拟 componentDidMount、componentDidUpdate 和 componentWillUnmount。
useState 和 useReducer 可以初始化 state,类似于 constructor。
useMemo 和 useCallback 可以优化性能,类似于 shouldComponentUpdate 的某些用例。
示例:
jsx
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    // 类似于 componentDidMount 和 componentDidUpdate
    document.title = `You clicked ${count} times`;

    // 类似于 componentWillUnmount
    return () => {
      // 清理操作
    };
  }, [count]); // 依赖项数组,类似于 shouldComponentUpdate

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
以上是 React 生命周期的详细解释以及各个阶段对应的代码示例。希望这能帮助你更好地理解 React 组件的生命周期。

 


http://www.ppmy.cn/news/1536020.html

相关文章

MobX-Miniprogram:微信小程序的状态管理利器

MobX-Miniprogram&#xff1a;微信小程序的状态管理利器 在开发微信小程序时&#xff0c;随着应用复杂度的提升&#xff0c;状态管理成为了一个不可忽视的问题。传统的通过全局变量或wx.setStorageSync/wx.getStorageSync进行状态管理的方式&#xff0c;不仅代码可读性差&…

Node.JS 版本管理工具 Fnm 安装及配置(Windows)

Fnm 安装及配置&#xff08;Windows&#xff09; Fnm&#xff08;Fast Node Manager&#xff09;&#x1f680; 一个快速而简单的 Node.js 版本管理工具&#xff0c;使用 Rust 编写。 1 安装 官网&#xff1a;Fnm&#xff08;镜像网站 &#xff09;。下载&#xff1a;Fnm&a…

【SQL】掌握SQL查询技巧:数据筛选与限制

目录 1. DISTINCT&#xff1a;避免重复记录1.1 示意图1.2 使用场景 2. LIMIT&#xff1a;控制查询结果的数量2.1 示意图2.2 使用场景 3. OFFSET&#xff1a;跳过前几行3.1 示意图3.2 使用场景 4. WHERE子句&#xff1a;精细控制数据过滤4.1 示意图4.2 运算符详细说明4.3 基本条…

hdfs伪分布式集群搭建

1 准备 vmware 虚拟三台centos系统的节点三台机器安装好jdk环境关闭防火墙&#xff08;端口太多&#xff0c;需要的自行去开关端口&#xff09;hadoop压缩包解压至三台服务器 可在一台节点上配置完成后克隆为三台节点 2 host修改 vi /etc/hosts在每个节点上添加三台机器的i…

IDEA创建、导入、删除maven项目

全局配置&#xff1a; 1.File->Close Project 2.Customize->All settings 3. Apply 4.选择JRE版本->Apply 5.选择字节码版本->Apply->OK 全局配置结束 创建maven项目&#xff1a; 1.File->New->Module 2.Build system选择Maven GroupId&#xff1a…

2024.10月7日- 非关系型数据库--- Redis

一、Redis介绍 Redis(Remote Dictionary Server)&#xff0c;即远程字典服务,也被人们称之为***结构化数据库*** 功能&#xff1a;把周期性数据持久化还能实现主从复制 是一个开源的用C语言编写的支持网络、基于内存、可持久化的日志型Key-Value数据库提供多种语言的API Re…

感知机学习算法

感知机 一、感知机简介二、感知机模型2.1 感知机的基本组成2.2 求和函数2.2.1 时间总合2.2.2 空间总合 2.3 激活函数2.4 学习算法2.4.1 赫布学习规则2.4.2 Delta学习规则 三、 结论参考文献 一、感知机简介 M-P神经元模型因其对生物神经元激发过程的极大简化而成为神经网络研究…

Python笔记之识别到当前python脚本所在的目录,而不是执行python命令的目录

Python笔记之识别到当前python脚本所在的目录&#xff0c;而不是执行python命令的目录 code review! 文章目录 Python笔记之识别到当前python脚本所在的目录&#xff0c;而不是执行python命令的目录1.题解2.在脚本所在的目录后面拼接下一层目录 1.题解 要在Python脚本中识别到…