React使用fetch报TypeError无法读取属性,Postman调用同API返回正常
问题原因
- 异步请求时序问题:fetch请求是异步执行的,组件第一次渲染时,请求还没有返回结果,
utilisations的初始值是空数组,此时访问utilisations[0]必然得到undefined,触发你遇到的TypeError。 - 赋值函数未执行:return代码块中的
{setDetails}只是输出函数对象本身,没有实际调用执行,四个展示用的变量永远停留在初始赋值的0。 - 普通变量无法触发重渲染:你用
var声明的四个变量不属于React的响应式状态,哪怕后续成功赋值,React也不会感知到变化触发组件重新渲染,页面不会更新为最新值。
修复方案
不需要额外定义变量和赋值函数,直接在渲染时判断utilisations是否有数据,有数据再读取对应字段展示即可,修复后代码如下:
import { useState, useEffect } from 'react'; function UtilisationDetail(props){ const [utilisations, setUtilisation] = useState([]); useEffect(()=>{ fetch(`http://127.0.0.1:8000/dashboard/utilisation/${props.warehouseState}/detail/get/`, { method:'GET', headers: { 'Content-Type': 'application/json' } }) .then(resp => resp.json()) .then(resp => setUtilisation(resp)) .catch(error => console.log(error)) }, [props.warehouseState]) // 直接判断数组长度,有数据再取对应字段 const data = utilisations.length ? utilisations[0] : {}; return( <div> <h4>Space</h4> <p>Average HB {data.average_hb || 0}</p> <p>Average OS {data.average_os || 0}</p> <p>Max HB {data.max_hb || 0}</p> <p>Max OS {data.max_os || 0}</p> </div> ) } export default UtilisationDetail;
补充优化
如果你需要先展示加载状态再渲染真实数据,避免用户先看到0再跳转为真实值,可以新增加载状态判断:
import { useState, useEffect } from 'react'; function UtilisationDetail(props){ const [utilisations, setUtilisation] = useState([]); const [loading, setLoading] = useState(true); useEffect(()=>{ fetch(`http://127.0.0.1:8000/dashboard/utilisation/${props.warehouseState}/detail/get/`, { method:'GET', headers: { 'Content-Type': 'application/json' } }) .then(resp => resp.json()) .then(resp => { setUtilisation(resp); setLoading(false); }) .catch(error => { console.log(error); setLoading(false); }) }, [props.warehouseState]) if(loading) return <div>数据加载中...</div> const data = utilisations.length ? utilisations[0] : {}; return( <div> <h4>Space</h4> <p>Average HB {data.average_hb || 0}</p> <p>Average OS {data.average_os || 0}</p> <p>Max HB {data.max_hb || 0}</p> <p>Max OS {data.max_os || 0}</p> </div> ) } export default UtilisationDetail;
内容的提问来源于stack exchange,提问作者lekocast
相关产品推荐
相关产品推荐

