React中使用Axios调用API报cannot read properties of undefined错误如何解决
问题原因与修复方案
- 该报错属于渲染阶段错误,并非Axios请求抛出,所以不会被请求的catch逻辑捕获。你给
poststate设置的初始值为[''],组件首次渲染时会遍历这个数组,第一个元素是空字符串,本身不存在owner属性,访问post.owner.picture时就会触发你看到的报错。 - 第一步修复初始值配置:将
const [post, setPost] = useState(['']);修改为const [post, setPost] = useState([]);。空数组首次渲染时不会执行map的回调逻辑,不会触发报错,等Axios请求拿到接口数据更新state后,再正常渲染帖子列表。 - 推荐补充两个优化点,避免极端场景报错同时提升用户体验:
- 新增加载状态控制,请求完成前展示加载提示,避免页面空屏
- 访问深层嵌套属性时使用可选链
?.做兼容,就算接口返回的某条帖子数据缺失owner字段,也不会直接导致页面崩溃
修改后参考代码
const key = '618479acc2ef5ba8018516ac' import { useState, useEffect } from 'react'; import axios from 'axios'; // 这里补充你用到的其他组件导入,比如Box、Grid、Card等 function UserPost1 () { const [post, setPost] = useState([]); const [loading, setLoading] = useState(true); // 你原代码未定义expanded状态,这里补充避免额外报错 const [expanded, setExpanded] = useState(false); const handleExpandClick = () => { setExpanded(!expanded); }; useEffect(() =>{ axios.get('https://dummyapi.io/data/v1/post' , { headers: { 'app-id': key } }) .then(res => { setPost(res.data.data) }) .catch(err =>{ console.log(err) }) .finally(() => { setLoading(false); }) },[]); if(loading) return <div>加载中...</div> return( <div className="Post-style"> {post.map(post =>( <Box sx={{ flexGrow: 1 }} key={post.id}> <Grid container rowSpacing={0} columnSpacing={{ xs: 1, sm: 2, md: 2, lg: 2 }} > <Grid container direction="row" justifyContent="center"> <Grid item xs={4} sm={12} md={6} lg={4}> <div className="card-Style"> <Card sx={{ width: 355}} style={{backgroundColor: "aquamarine"}} > <CardHeader avatar={ <Avatar src={post.owner?.picture} /> } action={ <IconButton aria-label="settings"> <MoreVertIcon /> </IconButton> } title={`${post.owner?.firstName || ''} ${post.owner?.lastName || ''}`} subheader={post.publishDate} /> <CardMedia component="img" height="194" image={post.image} alt="帖子配图" backgroundcolor="blue" /> <CardContent> <Typography variant="body2" color="text.secondary"> {post.text} <br></br> {post.likes} 赞 <br></br> {post.tags?.join('、')} </Typography> </CardContent> </Card> </div> </Grid> </Grid> </Grid> </Box> ))} </div> ) } export default UserPost1;
补充说明:原代码map遍历未给子元素加key属性,上述代码已一并补充,避免React抛出key相关警告。
内容的提问来源于stack exchange,提问作者RDK
相关产品推荐
相关产品推荐

