React报错:TypeError: Cannot read properties of undefined (reading '0') 求助
修复React中axios请求后的
TypeError: Cannot read properties of undefined (reading '0')错误 问题场景
我在开发React应用时,通过axios发送GET请求从Node.js后端获取数据,后端API和前端代码如下。应用能正常运行且所需的companyLogo数据已成功获取,但控制台一直报错:TypeError: Cannot read properties of undefined (reading '0'),需要排查前端代码问题修复这个错误。
后端Node.js代码
// NodeJS Backend app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { // GET - Company by User UUID const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)'; connection.query(selectQuery, [req.params.user_uuid], (err, results) => { if(err) { res.send(err) } else if (results.length === 0) { res.json({status: 404, message: 'Company not found'}) } else { res.json({data: results}) } }); });
前端React代码
// ReactJS FrontEnd const companyLogo = userCompany ? userCompany.logo_url : null; console.log(userCompany); useEffect(() => { const getUserCompany = async () => { try { await axios.get(process.env.REACT_APP_API_URL + 'companys/user/' + userUuid).then((response) => { console.log("response "+ response); let res = response.data.data[0]; console.log(res); setUserCompany(res); }); } catch (error) { console.log(error); } }; getUserCompany(); }, [userUuid]);
错误原因
报错的核心是后端返回404响应时,response.data中没有data字段。看后端逻辑:当查询不到公司数据时,返回的是{status: 404, message: 'Company not found'},此时前端直接访问response.data.data[0],会因为response.data.data是undefined而抛出读取下标0的错误。
另外,你同时混用了await和.then()写法,虽然功能正常,但属于冗余写法,容易混淆逻辑。
修复方案
1. 前端增加字段存在性判断
修改axios请求的处理逻辑,先检查response.data.data是否存在,再访问数组下标:
useEffect(() => { const getUserCompany = async () => { try { // 替换成模板字符串,更简洁 const response = await axios.get(`${process.env.REACT_APP_API_URL}companys/user/${userUuid}`); console.log("response", response); // 先判断data字段是否存在,再处理数据 if (response.data.data) { const res = response.data.data[0]; console.log(res); setUserCompany(res); } else { // 处理404场景,比如清空状态或提示用户 setUserCompany(null); console.log(response.data.message); } } catch (error) { console.log(error); // 处理网络错误等请求失败场景 setUserCompany(null); } }; getUserCompany(); }, [userUuid]);
2. 统一后端响应格式(推荐)
为了避免前端处理不同结构的响应,建议后端统一返回格式,无论成功失败都包含data字段:
// 修改后端代码 app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)'; connection.query(selectQuery, [req.params.user_uuid], (err, results) => { if(err) { res.status(500).json({status: 500, message: 'Server error', data: null}) } else if (results.length === 0) { res.status(404).json({status: 404, message: 'Company not found', data: null}) } else { res.status(200).json({status: 200, message: 'Success', data: results}) } }); });
这样前端可以安全访问response.data.data,即使错误场景也不会出现undefined。
3. 优化Logo渲染逻辑(可选)
给userCompany设置初始值,并使用可选链操作符简化判断:
// 初始化userCompany为null const [userCompany, setUserCompany] = useState(null); // 用可选链避免访问undefined的属性 const companyLogo = userCompany?.logo_url || null;
内容的提问来源于stack exchange,提问作者anto6314
相关产品推荐
相关产品推荐

