You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React无法展示数据,刷新时报Cannot read properties of undefined (reading 'id')错误

报错根因

  • 组件初始化时loading状态默认值为false,首次渲染会直接执行<MostrarProducto/>组件,此时useEffect里的接口请求还未触发,producto的初始值是空数组[],不存在data属性,访问producto.data返回undefined,再读取id就抛出了这个类型错误。热更新时React会保留组件已有状态,producto已经有接口返回的数值,所以不会触发报错,刷新页面后组件重新初始化,就会复现问题。

修复方案

你可以按照以下步骤修改代码:

  1. 将loading的初始值调整为true,避免首次渲染直接加载商品展示组件
  2. 将producto的初始值调整为和接口返回结构对齐的空对象,避免类型不匹配
  3. 访问深层嵌套属性时增加可选链?.做兜底,避免属性不存在时直接抛出错误

修改后完整代码

import React, { useState, useEffect } from "react";
import ProductoService from "../../../api/producto.service";
import { useParams } from "react-router-dom";

const VerProducto = () => {
  const {id} = useParams();
  // 调整初始值
  const [producto, setProducto] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const getProducto = async () => {
      setLoading(true);
      const res = await ProductoService.get(id);
      setProducto(res.data);
      setLoading(false);
    }
    getProducto();
  }, [id]);

  const Loading = () => {
    return(
      <>
        cargando...
      </>
    )
  }

  const MostrarProducto = () => {
    return(
      <>
        {/* 可选链兜底 */}
        <h1>{producto.data?.id}</h1>
      </>
    )
  }

  return (
    <div className="contenido">
      {loading? <Loading/> : <MostrarProducto/>}
    </div>
  );
}

export default VerProducto;

内容的提问来源于stack exchange,提问作者alin11g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:06:03