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 函数在组件挂载后和每次更新后都会调用,用于更新文档标题。

相关推荐
cn_mengbei20 小时前
用React Native开发OpenHarmony应用:Reanimated共享元素过渡
javascript·react native·react.js
We་ct1 天前
React 性能优化精讲
前端·javascript·react.js·性能优化·前端框架·html·浏览器
光影少年1 天前
前端在页面渲染优化和组件优化经验?
前端·vue.js·react.js·前端框架
Wect2 天前
React 性能优化精讲
前端·react.js·性能优化
光影少年2 天前
react性能优化比较好的办法有哪些?
前端·react.js·性能优化
Ww.xh2 天前
Figma设计稿转React代码:ClaudeCode+MCP实战教程
前端·react.js·figma
朝阳392 天前
react【实战】自定义下拉框、单选、多选、输入框
前端·javascript·react.js
IT枫斗者3 天前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
倾颜3 天前
React 19 源码主线拆解 04:Fiber 到底是什么,React 为什么需要 Fiber?
前端·react.js·源码阅读
老王以为3 天前
为什么 React 和 Vue 不一样?
前端·vue.js·react.js