基于输入获取GitHub单个用户时触发404错误,请求排查代码问题
问题排查:未输入内容触发GitHub API 404错误
问题描述
我尝试通过输入框内容获取GitHub单个用户数据,但还未在输入框中输入内容就出现了404错误,不清楚原因。
错误信息:
XHRGET https://api.github.com/users/ [HTTP/2 404 142ms]
原代码
import { useState, useEffect } from "react"; import "./FormComponent.scss"; const FormComponent = () => { const [user, setUser] = useState(""); const [profile, setProfile] = useState([]); const submitForm = (e) => { e.preventDefault(); setUser(""); }; useEffect(() => { let fetData = async () => { try { let response = await fetch(`https://api.github.com/users/${user}`); console.log(response); const users = await response.json(); setProfile(users); } catch (error) { console.log(error.message); } }; fetData(); }, []); return ( <div className="FormComponent"> <form onSubmit={submitForm}> <input onChange={(e) => setUser(e.target.value)} type="text" value={user} /> {profile.map((e) => console.log(e))} <button>Search</button> </form> </div> ); }; export default FormComponent;
问题原因及修复方案
核心问题1:组件挂载时自动发起空请求
你的useEffect依赖项是空数组[],这会导致组件一渲染就执行fetData函数。此时user的初始值是空字符串,拼接后请求URL变成https://api.github.com/users/,GitHub API找不到这个资源,直接返回404。
核心问题2:请求逻辑和搜索按钮完全脱节
当前代码里的submitForm只是清空输入框,根本没触发请求;反而组件一加载就乱发起请求,逻辑完全搞反了。
额外问题:状态类型不匹配
profile初始值设为数组[],但GitHub用户接口返回的是单个用户对象,后续用map遍历数组的操作完全无效,还会报错。
修复后的代码
import { useState } from "react"; import "./FormComponent.scss"; const FormComponent = () => { const [user, setUser] = useState(""); const [profile, setProfile] = useState(null); // 改为null适配单个对象结构 // 把请求逻辑移到提交函数里,点击搜索才触发 const submitForm = async (e) => { e.preventDefault(); // 先判断输入是否为空,避免无效请求 if (!user.trim()) return; try { const response = await fetch(`https://api.github.com/users/${user}`); // 主动判断响应状态,处理用户不存在的情况 if (!response.ok) { throw new Error("用户不存在或请求失败"); } const userData = await response.json(); setProfile(userData); // 可选:清空输入框 setUser(""); } catch (error) { console.log(error.message); setProfile(null); // 错误时重置状态 } }; return ( <div className="FormComponent"> <form onSubmit={submitForm}> <input onChange={(e) => setUser(e.target.value)} type="text" value={user} placeholder="输入GitHub用户名" /> <button type="submit">Search</button> </form> {/* 示例:渲染用户信息 */} {profile && ( <div className="user-card"> <img src={profile.avatar_url} alt={profile.login} width="80" /> <h3>{profile.login}</h3> <p>公开仓库数:{profile.public_repos}</p> <p>关注者:{profile.followers}</p> </div> )} </div> ); }; export default FormComponent;
修复要点总结
- 删掉了导致自动请求的
useEffect,把请求逻辑绑定到搜索按钮的提交事件上 - 增加输入空值判断,避免发起无效请求
- 调整
profile初始状态为null,适配接口返回的单个对象 - 补充响应状态校验,处理用户不存在等异常情况
- 替换了原有的无效
map遍历,添加了实际的用户信息渲染示例
内容的提问来源于stack exchange,提问作者joey
相关产品推荐
相关产品推荐

