React 组件生命周期函数的用法和示例代码

React 中的生命周期函数可以分为三个阶段:Mounting(挂载),Updating(更新)和 Unmounting(卸载)。每个阶段都有不同的函数,用于执行不同的操作。

  1. Mounting(挂载)

Mounting 阶段是组件实例化并插入到 DOM 中的阶段。在这个阶段中,有以下几个函数:

  • constructor():构造函数,用于初始化组件的 state 和绑定事件处理函数。
javascript 复制代码
constructor(props) {
  super(props);
  this.state = { count: 0 };
  this.handleClick = this.handleClick.bind(this);
}
  • static getDerivedStateFromProps():当组件接收到新的 props 时,会调用此函数,返回一个对象来更新 state,或者返回 null 表示不更新 state。
javascript 复制代码
static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.value !== prevState.value) {
    return { value: nextProps.value };
  }
  return null;
}
  • render():渲染组件到 DOM 中。
javascript 复制代码
render() {
  return (
    <div>
      <p>Count: {this.state.count}</p>
      <button onClick={this.handleClick}>Click me</button>
    </div>
  );
}
  • componentDidMount():组件挂载到 DOM 后调用,通常用于发送网络请求、设置定时器等操作。
javascript 复制代码
componentDidMount() {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}
  1. Updating(更新)

Updating 阶段是组件状态或属性更新时的阶段。在这个阶段中,有以下几个函数:

  • shouldComponentUpdate():当组件接收到新的 props 或 state 时,会调用此函数,返回 true 表示需要更新组件,返回 false 表示不需要更新组件。
javascript 复制代码
shouldComponentUpdate(nextProps, nextState) {
  if (nextProps.value !== this.props.value || nextState.count !== this.state.count) {
    return true;
  }
  return false;
}
  • static getDerivedStateFromProps():同 Mounting 阶段的 getDerivedStateFromProps() 函数。
  • render():同 Mounting 阶段的 render() 函数。
  • componentDidUpdate():组件更新后调用,通常用于操作 DOM 或发送网络请求。
javascript 复制代码
componentDidUpdate(prevProps, prevState) {
  if (prevProps.value !== this.props.value) {
    fetch(`https://api.example.com/data?value=${this.props.value}`)
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }
}
  1. Unmounting(卸载)

Unmounting 阶段是组件从 DOM 中移除的阶段。在这个阶段中,有以下几个函数:

  • componentWillUnmount():组件卸载前调用,通常用于清理定时器或取消网络请求等操作。
javascript 复制代码
componentWillUnmount() {
  clearTimeout(this.timer);
}

需要注意的是,在 React 16.8 之后,引入了 Hooks 的概念,可以使用 useEffect 等 Hook 来代替生命周期函数。例如:

javascript 复制代码
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

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

在这个例子中,useEffect 函数在组件挂载后和每次更新后都会调用,用于更新文档标题。

相关推荐
m0_528723811 小时前
在React中使用redux
前端·javascript·react.js
小乌龟快跑1 小时前
React Hooks 隔离机制和自定义 Hooks
react.js·面试
m0_5287238110 小时前
redex快速体验
react.js
Loong_DQX21 小时前
【react+redux】 react使用redux相关内容
前端·react.js·前端框架
GISer_Jing21 小时前
react redux监测值的变化
前端·javascript·react.js
m0_528723811 天前
react中useEffect的使用
前端·javascript·react.js
GISer_Jing1 天前
AIGC时代的Vue或React前端开发
vue.js·react.js·aigc
screct_demo1 天前
详细介绍 React Native 的动画系统。主要包括 Animated 组件的各种用法:
javascript·react native·react.js
Orange3015111 天前
React 19 新特性探索:提升性能与开发者体验
前端·javascript·react.js
GISer_Jing2 天前
前端面试&笔试题目(一)
前端·javascript·vue.js·react.js