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

Firebase Storage API触发两次问题排查求助

Firebase Storage API 触发两次问题排查与解决

核心原因:React 开发环境的 StrictMode 行为

在 React 18+ 的开发环境中,StrictMode 会刻意重复执行部分逻辑,用于检测组件的潜在副作用问题,包括:

  • 带有空依赖数组的 useEffect
  • 组件初始化相关代码
  • 状态更新函数

你的代码中,获取图片列表的 useEffect 会被执行两次,导致 listAll 和后续的 getDownloadURL 都触发两次 API 请求;另外上传完成后的状态更新也可能因组件重复渲染,间接引发重复逻辑执行。

具体修复方案

1. 解决 useEffect 重复触发 API 的问题

当前 useEffect 每次执行都会向 imageUrls 追加 URL,导致列表重复,可通过以下两种方式修复:

方案一:一次性收集所有 URL 再更新状态

useEffect(() => {
  // 先清空数组,避免重复添加
  setImageUrls([]);
  listAll(imagesListRef).then((response) => {
    const urlList = [];
    response.items.forEach((item) => {
      getDownloadURL(item).then((url) => {
        urlList.push(url);
        // 所有请求完成后一次性更新状态
        if (urlList.length === response.items.length) {
          setImageUrls(urlList);
        }
      });
    });
  });
}, []);

方案二:用 useRef 标记初始化状态

import { useEffect, useState, useRef } from "react";

function App() {
  const hasInitialized = useRef(false);
  // ... 其他状态定义

  useEffect(() => {
    // 仅初始化一次
    if (hasInitialized.current) return;
    hasInitialized.current = true;
    
    listAll(imagesListRef).then((response) => {
      response.items.forEach((item) => {
        getDownloadURL(item).then((url) => {
          setImageUrls((prev) => [...prev, url]);
        });
      });
    });
  }, []);

  // ... 其他代码
}

2. 上传逻辑优化(减少不必要渲染)

当前上传进度的状态更新会触发多次组件渲染,可优化为仅在进度变化时更新:

uploadTask.on(
  "state_changed",
  (snapshot) => {
    const progress = Math.round(
      (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    );
    // 仅在进度变化时更新状态
    if (progress !== progresspercent) {
      setProgresspercent(progress);
    }
  },
  (error) => {
    alert(error);
  },
  () => {
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      setImgUrl(downloadURL);
      // 上传完成后刷新图片列表
      setImageUrls([]);
      listAll(imagesListRef).then((response) => {
        response.items.forEach((item) => {
          getDownloadURL(item).then((url) => {
            setImageUrls((prev) => [...prev, url]);
          });
        });
      });
    });
  }
);

注意事项

StrictMode 的重复执行行为仅存在于开发环境,生产环境下 API 只会触发一次,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:40:37