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

相关推荐
ZoeLandia2 天前
React11:数据请求与 TanStack Query
前端·react.js·typescript·react
瓦瓦gogo2 天前
实习中接触前端开发后,我开始了解 React
前端·react.js·前端框架
ZoeLandia3 天前
React08:自定义 Hook
开发语言·前端·react.js·typescript
空中湖4 天前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
来一首_We_go6 天前
React Flow Pro 高级交互实现
前端·react.js
weedsfly6 天前
React 不可变数据:为什么页面“明明数据变了却不更新
前端·javascript·react.js
随风一样自由6 天前
【React+TS71007】Next.js “use client” 误用导致 TS71007:客户端/服务端引入问题的完整排查与修复
前端·javascript·react.js
ZoeLandia6 天前
React6:组件通信
前端·react.js·typescript
ZoeLandia7 天前
React03:useState 与不可变更新
前端·react.js·typescript·react
鬼手点金7 天前
单轮对话:最简单的 API 调用
java·服务器·前端·javascript·react.js·servlet·tomcat