React自定义Hook中obj.token判断失效导致返回failed问题求助
问题分析与解决方案
核心问题
你代码里的关键bug是重复读取了Response对象的响应体:
- 第一次
const obj = await response.json()已经把响应体的可读流消费完毕,Response对象的body只能被读取一次。 - 当你在条件判断通过后再次调用
await response.json()时,此时响应体已经是空的,这个调用会返回空对象甚至直接抛出错误,导致代码进入catch块,触发setFetchState('failed')。 - 你看到的
console.log('obj token', obj.token !== undefined)确实为true,但这行代码之后的重复读取响应体操作才是导致状态变为failed的元凶,和obj.token的判断本身无关。
修正代码
直接使用已经解析好的obj,不要再重复调用response.json():
const useMyHook = (url: string) => { const [fetchState, setFetchState] = useState('pending'); useEffect(() => { const fetchResponse = async () => { try { setFetchState('loading'); const response = await fetch(url); const obj = await response.json(); console.log('obj token', obj.token !== undefined); const isValidHeader = response.headers .get('Content-Type') ?.includes('application/json'); if (response.ok && isValidHeader && obj.token !== undefined) { console.log(obj); // 直接使用已解析完成的obj setFetchState('success'); // 修正拼写错误:succes → success } else { // 条件不满足时显式设置失败状态,避免停留在loading setFetchState('failed'); } } catch (error) { setFetchState('failed'); console.error(error); } }; fetchResponse(); }, [url]); // 依赖数组添加url,确保url变化时重新发起请求 return fetchState; }; export default useMyHook;
额外优化点
- 修复了状态值的拼写错误:
succes改为success - 给
useEffect的依赖数组补充url,保证传入的url更新时,Hook能重新触发请求 - 新增条件不满足时的状态设置逻辑,避免请求成功但不符合校验规则时,状态一直卡在
loading
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

