使用useState切换商品图片时出现“无法读取img属性”错误求助
问题排查与解决方案
核心错误原因
你遇到的cannot read properties of undefined (reading 'img')错误,大概率是以下两个原因之一:
1. API响应路径访问错误
Strapi的单个商品接口返回结构是外层包裹data字段,内部才是商品的attributes信息,示例结构如下:
{ "data": { "id": 1, "attributes": { "img": { "data": { "attributes": { "url": "xxx" } } }, "img2": { "data": { "attributes": { "url": "xxx" } } } } }, "meta": {} }
如果你的useFetch返回的是完整接口响应对象,当前代码直接访问data?.attributes是错误的——应该改为data?.data?.attributes,否则data.attributes会是undefined,后续访问img自然触发报错。
2. 未处理数据加载状态
useFetch是异步请求,组件初次渲染时data还未就绪(可能是undefined或null),虽然用了可选链,但如果不在loading状态下阻止渲染图片元素,仍可能触发意外的属性访问错误。
修复步骤
步骤1:修正API数据访问路径
将所有图片src中的data?.attributes替换为data?.data?.attributes(如果useFetch返回完整响应):
<div className="images"> <img src={ process.env.REACT_APP_UPLOAD_URL + data?.data?.attributes?.img?.data?.attributes?.url } alt="商品缩略图1" onClick={() => setSelectedImg("img")} /> <img src={ process.env.REACT_APP_UPLOAD_URL + data?.data?.attributes?.img2?.data?.attributes?.url } alt="商品缩略图2" onClick={() => setSelectedImg("img2")} /> </div> <div className="mainImg"> <img src={ process.env.REACT_APP_UPLOAD_URL + data?.data?.attributes[selectedImg]?.data?.attributes?.url } alt="商品主图" /> </div>
如果你的useFetch内部已经提取了响应的data字段(比如setData(res.data)),则保持data?.attributes即可,跳过此步骤。
步骤2:添加加载状态处理
在组件渲染前判断loading和error状态,避免在数据未就绪时渲染图片:
const Product = () => { const id = useParams().id; const [selectedImg, setSelectedImg] = useState("img"); const [quantitiy, setQuantitiy] = useState(1); const { data, loading, error } = useFetch(`/products/${id}?populate=*`); // 加载中显示占位符 if (loading) return <div>加载中...</div>; // 加载出错提示 if (error) return <div>加载失败:{error.message}</div>; // 确保商品数据存在 if (!data?.data?.attributes) return <div>商品不存在</div>; return ( // 你的页面渲染代码 ); }
步骤3:检查useFetch实现
确认useFetch返回的data结构是否符合预期:
- 如果它返回完整接口响应(包含
data和meta),则按步骤1修正路径; - 如果它已经返回商品具体数据(即
res.data),则确保初始data值为null或undefined,而非空对象{}——空对象会导致data.attributes为undefined,若后续漏写可选链就会触发错误。
内容的提问来源于stack exchange,提问作者ETF MERN
相关产品推荐
相关产品推荐

