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

API调用异常:切换动物/品种提交无响应,仅地点切换有效

问题修复:切换动物/品种后API请求无效

问题根源

当前代码构造API请求URL时,会直接拼接animal、location、breed三个参数,即便它们是空字符串。而目标API无法处理空值查询参数,导致切换动物或品种后提交的请求无法返回正确结果。

修复方案

修改requestPets函数,仅将非空参数添加到请求URL中,避免传递无效空参数给API。

修改后的代码

useEffect(() => {
  requestPets();
}, []);

async function requestPets() {
  // 构建仅包含非空值的查询参数对象
  const params = new URLSearchParams();
  if (animal) params.append('animal', animal);
  if (location) params.append('location', location);
  if (breed) params.append('breed', breed);

  const res = await fetch(
    `http://pets-v2.dev-apis.com/pets?${params.toString()}`
  );
  const json = await res.json();
  setPets(json.pets);
}

// 表单部分代码保持不变
<form
  onSubmit={(e) => {
    e.preventDefault();
    requestPets();
  }}
>
<label htmlFor="location">
  Location
  <input
    onChange={(e) => setLocation(e.target.value)}
    type="text"
    id="location"
    value={location}
    placeholder="Location"
  />
  </label>
  <label htmlFor="animal">
    Animal
    <select
      name=""
      id="animal"
      value={animal}
      onChange={(e) => {
        setAnimal(e.target.value);
        setBreed("");
      }}
    >
      <option />
      {ANIMALS.map((animal) => (
        <option key={animal}>{animal}</option>
      ))}
    </select>
  </label>

  <label htmlFor="breed">
    Breed
    <select
      name=""
      disabled={breeds.length === 0}
      id="breed"
      value={breed}
      onChange={(e) => setBreed(e.target.value)}
    >
      <option />
      {breeds.map((breed) => (
        <option key={breed}>{breed}</option>
      ))}
    </select>
  </label>
  <button>Search</button>
</form>

说明

  • 使用URLSearchParams可安全规范地构建查询字符串,自动处理参数编码问题。
  • 通过条件判断过滤空值参数,确保API仅接收有效查询条件,避免空参数导致的请求异常。
  • 表单交互逻辑无需修改,提交时仍会调用更新后的requestPets函数,使用最新state值构建请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:13:13