react类生命周期和hooks生命周期详解

在 React 中,类组件和函数组件有不同的生命周期方法或钩子(Hooks)。了解它们对于开发和优化 React 应用非常重要。以下是两者的详细解释。

类组件生命周期方法

在类组件中,生命周期方法分为三个主要阶段:挂载(Mounting)、更新(Updating)和卸载(Unmounting)。

挂载(Mounting)
  1. constructor()

    • 在组件实例化时调用。通常用于初始化状态和绑定方法。

    • 示例:

      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
      
  2. componentDidMount()

    • 组件挂载后立即调用。通常用于网络请求、订阅等副作用。

    • 示例:

      componentDidMount() {
        // 例如,获取数据
        fetch('/api/data')
          .then(response => response.json())
          .then(data => this.setState({ data }));
      }
      
更新(Updating)
  1. shouldComponentUpdate(nextProps, nextState)

    • 在重新渲染前调用。返回 truefalse,决定是否更新组件。

    • 示例:

      shouldComponentUpdate(nextProps, nextState) {
        return nextState.count !== this.state.count;
      }
      
  2. componentDidUpdate(prevProps, prevState, snapshot)

    • 组件更新后立即调用。用于响应状态或属性的变化。

    • 示例:

      componentDidUpdate(prevProps, prevState) {
        if (prevState.count !== this.state.count) {
          // 例如,发送分析数据
          console.log(`Count updated to ${this.state.count}`);
        }
      }
      
卸载(Unmounting)
  1. componentWillUnmount()
    • 组件卸载前调用。用于清理订阅、定时器等。

    • 示例:

      componentWillUnmount() {
        // 例如,清理订阅
        clearInterval(this.interval);
      }
      

函数组件中的钩子(Hooks)

函数组件没有类组件的生命周期方法,但可以使用 Hooks 来实现相同的功能。

挂载和更新
  1. useEffect
    • useEffect 钩子结合了 componentDidMountcomponentDidUpdate 的功能。可以在组件渲染后执行副作用。

    • 示例:

      import React, { useEffect, useState } from 'react';
      
      function Example() {
        const [count, setCount] = useState(0);
      
        useEffect(() => {
          document.title = `You clicked ${count} times`;
        }, [count]); // 只有 count 变化时才会重新执行
      
        return (
          <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
              Click me
            </button>
          </div>
        );
      }
      
    • 清理副作用:类似于 componentWillUnmount,可以在 useEffect 中返回一个清理函数。

      useEffect(() => {
        const interval = setInterval(() => {
          setCount(c => c + 1);
        }, 1000);
      
        return () => clearInterval(interval); // 清理定时器
      }, []);
      
条件执行
  1. useMemo

    • 用于记忆化(缓存)计算结果,以优化性能。

    • 示例:

      import React, { useMemo, useState } from 'react';
      
      function ExpensiveComponent({ input }) {
        const computeExpensiveValue = (input) => {
          // 假设这是一个昂贵的计算
          return input * 2;
        };
      
        const memoizedValue = useMemo(() => computeExpensiveValue(input), [input]);
      
        return <div>{memoizedValue}</div>;
      }
      
  2. useCallback

    • 用于记忆化(缓存)回调函数,以避免不必要的重新渲染。

    • 示例:

      import React, { useCallback, useState } from 'react';
      
      function MyComponent() {
        const [count, setCount] = useState(0);
      
        const increment = useCallback(() => {
          setCount(count + 1);
        }, [count]);
      
        return (
          <div>
            <button onClick={increment}>Increment</button>
            <p>{count}</p>
          </div>
        );
      }
      

总结

类组件和函数组件都有自己的生命周期方法或钩子,以下是它们的对应关系:

类组件生命周期方法函数组件钩子
constructor初始化状态(useState
componentDidMountuseEffect(空依赖数组)
shouldComponentUpdate无直接对应(可以使用 React.memouseMemo 进行优化)
componentDidUpdateuseEffect(带依赖数组)
componentWillUnmountuseEffect 的清理函数
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暖阳浅笑-嘿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值