React从API取数报错:Cannot read properties of undefined (reading 'attributes')
问题排查与解决
核心原因
你的代码在初始渲染阶段就尝试访问project.attributes.Title,但此时API请求还未完成,project处于undefined状态,直接读取attributes必然抛出Cannot read properties of undefined错误。另外要注意,你的API返回结构包含data字段,必须先提取该字段再赋值给状态,否则也会导致后续属性访问异常。
具体解决步骤
1. 修正API返回数据的处理逻辑
API返回的内容嵌套在data字段中,需先解构提取后再更新状态:
// 修正后的fetch请求逻辑 fetch(`http://localhost:1337/api/projects/${id}`, { headers, method: 'GET' }) .then(res => res.json()) .then(response => { // 必须提取response.data,而非直接赋值整个response setProject(response.data); }) .catch(err => console.error('请求失败:', err));
2. 避免数据未加载时访问属性
提供三种实用方案:
方案一:使用可选链操作符(?.)
在属性访问路径中添加可选链,当project为undefined/null时会自动返回undefined,不会触发报错:
{project?.attributes?.Title}
方案二:条件渲染
先判断project是否存在,再渲染内容,同时可添加加载提示:
{project ? ( <div> <h1>{project.attributes.Title}</h1> {/* 其他属性渲染逻辑 */} </div> ) : ( <div>加载中...</div> )}
方案三:初始化状态为null或空结构
将project的初始状态设为null或包含空attributes的对象,避免初始值为undefined:
const [project, setProject] = useState(null); // 或者 const [project, setProject] = useState({ attributes: {} });
3. 优化请求触发逻辑
确保useEffect仅在id变化时发起请求,避免不必要的重复调用:
useEffect(() => { const fetchProject = async () => { try { const res = await fetch(`http://localhost:1337/api/projects/${id}`, { headers, method: 'GET' }); const response = await res.json(); setProject(response.data); } catch (err) { console.error('请求失败:', err); } }; fetchProject(); }, [id]); // 依赖项加入id,确保id变化时重新请求
额外说明
控制台多次打印undefined是正常现象:React组件会先以初始状态渲染一次,待API请求完成、状态更新后再重新渲染一次。
内容的提问来源于stack exchange,提问作者Jahs
相关产品推荐
相关产品推荐

