React组件的生命周期详解

yizhihongxing

React组件的生命周期可以分为三个阶段:

  1. 挂载阶段(Mounting)
  2. 更新阶段(Updating)
  3. 卸载阶段(Unmounting)

在接下来的讲解中,我们将深入探讨每个阶段的具体生命周期函数及其作用。同时,我们也会为每个函数提供示例说明。

挂载阶段(Mounting)

在组件挂载之前和之后,React会依次调用以下生命周期函数:

constructor(props)

constructor是生命周期的第一个函数,这个函数是ES6类中的构造函数。此函数在组件创建时被调用,并将props通过参数传入构造函数。

示例:创建一个类,输出props到控制台

class MyComponent extends React.Component {
  constructor(props){
    super(props);
    console.log("props: ", props);
  }
  render() {
    return <div>Hello React!</div>;
  }
}

static getDerivedStateFromProps(props, state)

这个函数在组件挂载之前、更新之前,以及父组件传递的props发生变化时被调用。它接收props和state两个参数,用于控制组件的状态。返回一个对象来更新state。

示例:通过getDerivedStateFromProps更新state

class MyComponent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      count: props.initialCount
    };
  }
  static getDerivedStateFromProps(props, state) {
    return {
      count: props.initialCount
    };
  }
  render() {
    return <div>Count: {this.state.count }</div>;
  }
}

render()

render函数是React组件的核心函数,用于返回组件的渲染结果。render应该是一个纯函数,它不应该产生副作用,也不应该调用组件的其他函数。

示例:返回一段HTML代码

class MyComponent extends React.Component {
  render() {
    return <div>Hello React!</div>;
  }
}

componentDidMount()

componentDidMount函数在组件挂载后立即调用。一般情况下,该函数用于进行网络请求、初始化第三方库等操作。

示例:在组件挂载后调用setInterval

class MyComponent extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({
      date: new Date()
    });
  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

更新阶段(Updating)

在组件更新之前和之后,React会依次调用以下生命周期函数:

static getDerivedStateFromProps(props, state)

同挂载阶段中的getDerivedStateFromProps方法,只是在组件更新时被调用。

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate函数用于控制组件是否进行更新。如果该函数返回false,则不会调用组件的render函数,也不会触发后续的更新函数;如果该函数返回true,则继续更新组件。默认情况下,该函数返回true。

示例:通过shouldComponentUpdate控制组件更新

class MyComponent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      count: 0
    };
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.count === nextState.count) {
      return false;
    }
    return true;
  }
  handleClick = () => {
    this.setState({
      count: this.state.count + 1
    });
  };
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click me</button>
        <div>Count: {this.state.count}</div>
      </div>
    );
  }
}

render()

同挂载阶段中的render方法。

getSnapshotBeforeUpdate(prevProps, prevState)

getSnapshotBeforeUpdate函数在组件更新之前调用。它接收两个参数:prevProps和prevState,用于获取更新前的props和state。该函数的返回值将作为第三个参数传递给componentDidUpdate函数。

示例:通过getSnapshotBeforeUpdate获取滚动条位置

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevProps.users.length < this.props.users.length) {
      const container = this.myRef.current;
      return container.scrollHeight - container.scrollTop;
    }
    return null;
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot !== null) {
      const container = this.myRef.current;
      container.scrollTop = container.scrollHeight - snapshot;
    }
  }
  render() {
    return (
      <div ref={this.myRef} style={{ height: "100px", overflow: "auto" }}>
        {this.props.users.map((user) => (
          <div>{user}</div>
        ))}
      </div>
    );
  }
}

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate函数在组件更新后调用。它接收三个参数:prevProps、prevState和snapshot。用于处理更新后的操作:例如重新请求数据、改变各种状态等。

示例:在组件更新后触发弹窗

class MyComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.isVisible !== this.props.isVisible && !this.props.isVisible) {
      alert('Modal hidden!') // 弹窗提示
    }
  }
  render() {
    return (
      <div>{this.props.isVisible && <div className="modal">Modal content goes here.</div>}</div>
    );
  }
}

卸载阶段(Unmounting)

在组件卸载之前,React只会调用一个生命周期函数:

componentWillUnmount()

componentWillUnmount函数在组件卸载之前调用。一般情况下,该函数用于释放组件占用的资源、停止定时器等。

示例:在组件卸载时停止计时器

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.timerID = null;
    this.state = {
      count: 0
    };
  }
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({
      count: this.state.count + 1
    });
  }
  render() {
    return (
      <div>
        Count: {this.state.count}
      </div>
    );
  }
}

以上就是React组件的完整生命周期,其中的每个生命周期函数都有着不同的作用。在实际编码过程中,我们应该根据实际需求,选择合适的生命周期函数来处理组件相关的操作。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:React组件的生命周期详解 - Python技术站

(0)
上一篇 2023年6月27日
下一篇 2023年6月27日

相关文章

  • 一篇文章搞懂:词法作用域、动态作用域、回调函数及闭包

    一篇文章搞懂:词法作用域、动态作用域、回调函数及闭包 词法作用域(Lexical Scope) 词法作用域是指变量的可见性和访问规则是在代码编写阶段就确定的。在词法作用域中,变量的作用域是由它们在代码中的位置决定的,而不是在运行时决定的。 示例1: function outer() { var x = 10; function inner() { conso…

    other 2023年8月16日
    00
  • gulp安装和使用简介

    以下是Gulp安装和使用简介的完整攻略,包括两个示例说明。 1. Gulp简介 Gulp是一个基于Node.js的自动化构建工具,可以帮助开发者自动化执行常见的开发任务,例如编译Sass、压缩JavaScript、优化图像等。Gulp使用简单、灵活,可以大大提高开发效率。 2. Gulp安装 以下是在Linux系统中安装Gulp的步骤: 安装Node.js:…

    other 2023年5月9日
    00
  • VisualStudio怎么设置控件格式?

    设置控件格式是制作GUI应用程序的一个重要步骤,可以让用户在使用程序时更加舒适和方便。以下是Visual Studio设置控件格式的详细攻略: 步骤一:打开表单编辑器 在Visual Studio的菜单中,选择“视图”,再选择“表单设计器”,或者在解决方案资源管理器中右键单击表单代码文件,选择“设计器”即可打开表单编辑器。 步骤二:添加控件 在表单编辑器中可…

    other 2023年6月27日
    00
  • Redis集群的关闭与重启操作

    Redis集群的关闭与重启操作过程如下: 1. 关闭Redis集群 1.1 单个节点关闭 可使用如下命令关闭单个节点: redis-cli -p port shutdown 其中,port为该节点的端口号,执行该命令后,该节点将会被关闭。 1.2 整个集群关闭 若需要关闭整个Redis集群,可按如下步骤进行: 首先停止Redis客户端的对外服务 然后逐个停止…

    other 2023年6月27日
    00
  • js onload处理html页面加载之后的事件

    介绍 JS Onload 处理 HTML 页面加载之后的事件,需要分以下几个方面进行说明: Javascript onload事件的概念和基本语法 如何使用Javascript的onload事件 JS onload事件的应用场景 1. Javascript onload事件的概念和基本语法 JS Onload 是Javascript的事件之一。它的含义是:当…

    other 2023年6月25日
    00
  • C语言的常量,字符串,转义字符,注释你都了解吗

    当然!下面是C语言常量、字符串、转义字符、注释的详细讲解: 常量 常量是指在程序运行过程中不会改变其值的数据。C语言中有以下几种类型的常量: 整型常量:整型常量是指不带小数的数字,例如123,456等。 实型常量:实型常量是指带小数的数字,例如12.34,56.78等。 字符常量:字符常量是指用单引号括起来的单个字符,例如’a’,’b’等。 布尔常量:布尔常…

    other 2023年6月20日
    00
  • 数据库性能测试之sysbench工具的安装与用法详解

    数据库性能测试之sysbench工具的安装与用法详解 简介 sysbench是一个常用的开源数据库性能测试工具,可以用于测试数据库的吞吐量、延迟、并发性等性能指标。本攻略将详细介绍sysbench工具的安装和用法。 步骤1:安装sysbench工具 首先,我们需要安装sysbench工具。以下是在Ubuntu系统上安装sysbench的示例命令: sudo …

    other 2023年10月16日
    00
  • 最新MySql8.27主从复制及SpringBoot项目中的读写分离实战教程

    以下是关于最新MySQL 8.27主从复制及Spring Boot项目中的读写分离实战教程的完整攻略,包含两个示例说明: 1. MySQL 8.27主从复制配置 步骤一:配置主数据库 在主数据库的配置文件(my.cnf)中,启用二进制日志功能,并设置唯一的服务器ID。 创建一个用于复制的用户,并为其授予复制权限。 示例代码: [mysqld] server-…

    other 2023年10月18日
    00
合作推广
合作推广
分享本页
返回顶部