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
相关产品推荐
相关产品推荐

