You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将使用componentWillReceiveProps的类组件重写为React函数式组件

重构后的函数式组件代码
import React, { useState, useEffect } from "react";

const Thumbnail = ({ file }) => {
  const [loading, setLoading] = useState(false);
  const [thumb, setThumb] = useState(undefined);

  useEffect(() => {
    if (!file) return;

    setLoading(true);
    const reader = new FileReader();

    reader.onloadend = () => {
      setLoading(false);
      setThumb(reader.result);
    };

    reader.readAsDataURL(file);

    // 清理逻辑:避免组件卸载/文件变更时的内存泄漏与无效状态更新
    return () => {
      reader.abort();
    };
  }, [file]);

  if (!file) return null;
  if (loading) return <p>loading...</p>;

  return (
    <img
      src={thumb}
      alt={file.name}
      className="img-thumbnail mt-2"
      height={200}
      width={200}
    />
  );
};

export default Thumbnail;
关键逻辑说明
  • 状态替换:使用useState Hook 替代类组件中的state对象,分别声明loading和thumb两个状态
  • componentWillReceiveProps逻辑替换:使用useEffect Hook,将file作为依赖项,只有file props发生变化时才会执行文件读取的逻辑,比原类组件的实现更精准,不会被其他无关props的变化触发
  • 优化项:新增useEffect清理逻辑,解决原类组件可能存在的文件读取未完成时组件卸载,导致的无效状态更新警告问题

内容的提问来源于stack exchange,提问作者osint_alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:36:00