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

React中使用State作为API请求参数时出现Error 400问题求助

问题分析与修复方案

核心问题1:模板字符串语法错误

你在请求URL里写了${{location}},这是错误写法——模板字符串插入变量只需要一层大括号${location},双大括号是JSX专属语法,在这里会把location包裹成对象,最终请求的q参数值会变成[object Object],API接收到无效地点参数,自然返回400错误。

核心问题2:useCallback依赖缺失

fetchweatherHandler用了useCallback但依赖数组是空的,这会导致函数内部的location一直停留在初始值"Mumbai",哪怕用户通过locationHandler更新了地点,函数读取的还是旧值,请求不会使用新参数。

核心问题3:请求触发时机不对

当前useEffect依赖fetchweatherHandler,但因为useCallback依赖未更新,当location变化时,fetchweatherHandler不会重新创建,useEffect也不会触发新请求。


修正后的代码

const [weather, setWeather] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [location, setLocation] = useState("Mumbai"); // 变量名调整为更规范的setLocation

const locationHandler = (place) => {
  setLocation(place);
};

const fetchweatherHandler = useCallback(async () => {
  setIsLoading(true);
  setError(null);
  try {
    console.log(location);
    // 修复模板字符串的变量插入语法
    const response = await fetch(
      `http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${location}&aqi=yes`
    );

    if (!response.ok) {
      throw new Error("Something went wrong!");
    }

    const data = await response.json();
    console.log(data);
    setWeather(data);
  } catch (error) {
    setError(error.message);
  }
  setIsLoading(false);
}, [location]); // 加入location作为依赖,确保地点变化时函数更新

// 直接监听location变化触发请求,逻辑更直观
useEffect(() => {
  fetchweatherHandler();
}, [fetchweatherHandler, location]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:55:40