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

React Vite TSX项目中如何避免代码修改时触发API调用

解决开发环境下API调用额度耗尽的问题

1. 开发环境启用Mock数据

通过Vite自带的环境变量判断开发模式,直接返回模拟数据,彻底避免真实API调用:

useEffect(() => {
  const fetchData = async () => {
    // 开发环境直接用模拟数据
    if (import.meta.env.DEV) {
      setData(72); // 模拟温度值
      setWeatherStatus({
        type: "SET_WEATHER_CODE",
        payload: 10001 // 模拟天气代码
      });
      return;
    }
    // 生产环境正常执行API调用逻辑
    try {
      const response = await axios.post(
        `${postWeatherURL}?apikey=${apiKey}`,
        {
          location,
          fields: ["temperature", "weatherCodeDay", "weatherCodeNight"],
          units: "imperial",
          timesteps,
          startTime,
        }
      );
      setData(
        response.data.data.timelines[0].intervals[0].values.temperature
      );
      if (date.getHours() >= 7 && date.getHours() < 19) {
        setWeatherStatus({
          type: "SET_WEATHER_CODE",
          payload:
            response.data.data.timelines[0].intervals[0].values
              .weatherCodeNight,
        });
      } else {
        setWeatherStatus({
          type: "SET_WEATHER_CODE",
          payload:
            response.data.data.timelines[0].intervals[0].values
              .weatherCodeDay,
        });
      }
    } catch (error) {
      console.error("Error retrieving weather data:", error);
    }
  };

  fetchData();
  const interval = setInterval(fetchData, 3 * 60 * 60 * 1000);

  return () => clearInterval(interval);
}, []);

2. 限制开发环境的API调用频率

如果不想完全用Mock,可以在开发模式下取消定时调用,仅在组件挂载时请求一次:

useEffect(() => {
  const fetchData = async () => {
    try {
      // 原API调用逻辑...
    } catch (error) {
      console.error("Error retrieving weather data:", error);
    }
  };

  fetchData();
  // 仅生产环境设置定时调用
  let interval;
  if (!import.meta.env.DEV) {
    interval = setInterval(fetchData, 3 * 60 * 60 * 1000);
  }

  return () => interval && clearInterval(interval);
}, []);

3. 本地缓存API响应

把API返回的数据存在localStorage,开发环境优先读取缓存,过期后再请求:

useEffect(() => {
  const fetchData = async () => {
    if (import.meta.env.DEV) {
      // 读取本地缓存
      const cachedTemp = localStorage.getItem('weatherTemp');
      const cachedCode = localStorage.getItem('weatherCode');
      if (cachedTemp && cachedCode) {
        setData(JSON.parse(cachedTemp));
        setWeatherStatus({
          type: "SET_WEATHER_CODE",
          payload: parseInt(cachedCode)
        });
        return;
      }
    }

    try {
      const response = await axios.post(
        `${postWeatherURL}?apikey=${apiKey}`,
        {
          location,
          fields: ["temperature", "weatherCodeDay", "weatherCodeNight"],
          units: "imperial",
          timesteps,
          startTime,
        }
      );
      const temp = response.data.data.timelines[0].intervals[0].values.temperature;
      const weatherCode = date.getHours() >=7 && date.getHours() <19 
        ? response.data.data.timelines[0].intervals[0].values.weatherCodeNight
        : response.data.data.timelines[0].intervals[0].values.weatherCodeDay;
      
      setData(temp);
      setWeatherStatus({ type: "SET_WEATHER_CODE", payload: weatherCode });

      // 开发环境缓存数据
      if (import.meta.env.DEV) {
        localStorage.setItem('weatherTemp', JSON.stringify(temp));
        localStorage.setItem('weatherCode', weatherCode.toString());
      }
    } catch (error) {
      console.error("Error retrieving weather data:", error);
    }
  };

  fetchData();
  const interval = setInterval(fetchData, 3 * 60 * 60 * 1000);

  return () => clearInterval(interval);
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:48:17