深入了解 React 组件的生命周期

news/2024/7/15 19:18:45 标签: react.js, 前端, 前端框架

在 React 中,每当我们创建一个新的组件时,都会经历一系列的步骤,这被称为生命周期。React 为我们提供了一系列生命周期方法,可以让我们跟踪这些步骤并添加相应的逻辑。
下面是常见的生命周期方法:

  • constructor()
  • componentDidMount()
  • componentWillUnmount()
  • componentDidUpdate()
  • shouldComponentUpdate()
  • componentDidCatch()
  • getDerivedStateFromProps()
  • getSnapshotBeforeUpdate()
  • render()
    constructor():在组件第一次被加载的时候调用,在此期间可以初始化状态、绑定事件等。
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'John'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {}
  
  render() {}
}

componentDidMount():组件在首次渲染完成后调用,可以在这里发起 AJAX 请求或者添加事件监听器。

class MyComponent extends React.Component {
  componentDidMount() {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => this.setState({data}));
  }
  
  render() {}
}

componentWillUnmount():组件即将从 dom 中移除时调用,可以在此时清除定时器或者取消网络请求。

class MyComponent extends React.Component {
  componentWillUnmount() {
    clearTimeout(this.timeoutId);
  }
  
  render() {}
}

componentDidUpdate(prevProps, prevState):组件重新-render之后调用,在这里可以检查 props 和 state 是否发生改变,从而作出反应。

class MyComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.data !== this.props.data || prevState.name !== this.state.name) {
      console.log('数据或状态发生了改变!');
    }
  }
  
  render() {}
}

shouldComponentUpdate(nextProps, nextState): 返回一个布尔值,如果 true,则会进行重新渲染,否则跳过渲染。

class MyComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps.data !== this.props.data || nextState.name !== this.state.name;
  }
  
  render() {}
}

getDerivedStateFromProps(nextProps, nextState):在每次渲染之前被调用,可以在这里计算新状态并返回一个新的对象。

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, nextState) {
    const newState = {};
    if (nextProps.data !== this.props.data) {
      newState.data = nextProps.data;
    }
    
    return newState;
  }
  
  render() {}
}

getSnapshotBeforeUpdate(prevProps, prevState):在 componentDidUpdate 之前调用,可以在此时返回一个值,然后在 componentDidUpdate 中使用这个值。

class MyComponent extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    return prevProps.data !== this.props.data;
  }
  
  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot) {
      console.log('数据已经改变了!');
    }
  }
  
  render() {}
}

render(): 组件的主要职责,返回的是一个 JSX 元素。
React 生命周期是一个非常重要的话题,熟练掌握生命周期方法可以更好地管理和优化组件的状态和行为。以上就是在 React 中使用生命周期的一些基本概念和使用方法,请多多实践!


http://www.niftyadmin.cn/n/5168931.html

相关文章

基于Python的pyAV读取H265(HEVC)编码的视频文件

1.问题出现 利用海康威视相机拍出来的视频是H265格式的,相比于常规的H264编码,压缩率更高,但因此如果直接用之前的方法读取,会出现无法读取的情况,如下。 可以看到,对于帧间没有改变的部分&#xf…

Python查验身份证

一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下: 首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1&am…

什么是 CASB,在网络安全中的作用

数字化转型正在稳步攀升,组织现在越来越关注在线生产力系统和协作平台,各行各业的企业都采用了不同的云基础设施服务模式。云基础架构提供按需服务,可提高易用性、访问控制、内容协作和减少内部存储资源,以及许多其他好处。迁移到…

图论——Dijkstra算法matlab代码

Dijkstra算法步骤 (1)构造邻接矩阵 (2)定义起始点 (3)运行代码 M=[ 0 5 9 Inf Inf Inf InfInf 0 Inf Inf 12 Inf InfInf 3 0 15 Inf 23 InfInf 6 Inf 0 Inf 8 7Inf 12 Inf 5 0 I…

管理员模式运行cmd或则bat文件的时候,出现路径错误的问题

最近在使用Comfyui, 不清楚啥原因,有时候Git无法访问,有时候文件夹无法访问的。就想把它的运行bat命令直接用 管理员模式运行,给到最高的权限,试试。但就这么简单的问题,搜了半天,都是一大堆不靠谱的教程&a…

Unity中Shader雾效的原理

文章目录 前言一、我们先看一下现实中的雾二、雾效的混合公式最终的颜色 lerp(雾效颜色,物体颜色,雾效混合因子) 三、雾效的衰减1、FOG_LINEAR(线性雾衰减)2、FOG_EXP(指数雾衰减1)3、FOG_EXP(指数雾衰减2) 前言 Unity中Shader雾…

Vue 循环el-select 并且不能重复选择相同数据

根据已选择的属性 , 禁用相同属性的选项 ,如果重复则不能再选择 <template><div class"container"><h3>需求&#xff1a;一共4台车 每人只能选择不一样的车 选过的不能再选</h3><divv-for"(item, index) in person.model.selectList…

React通过属性 (props) 和状态 (state) 来传递和管理组件的数据

import React, { useState } from react;// 子组件 const ChildComponent (props) > {return (<div><h2>Hello, {props.name}!</h2></div>); }// 父组件 const ParentComponent () > {const [name, setName] useState(John Doe);const handle…