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

React商品详情页点击后空白,报slice与模块导入错误

问题排查与修复方案

错误1:Uncaught TypeError: Cannot read properties of undefined (reading 'slice')

核心原因

  • useState使用了错误的解构方式:useState返回数组而非对象,用对象解构会导致state无法正常更新。
  • 错误调用Redux的dispatch更新组件内部state:setItems是组件本地state的更新函数,不能通过dispatch调用,导致items未被正确赋值为数组,最终变为undefined。

修复步骤

  1. 修正useState解构语法:把所有对象解构改为数组解构:
// 错误写法
// const { value, setValue } = useState("description")
// 正确写法
const [value, setValue] = useState("description");
const [count, setCount] = useState(1);
const [item, setItem] = useState(null);
const [items, setItems] = useState([]);
  1. 正确更新组件本地state:在getItems函数中移除dispatch,直接调用setItems:
async function getItems() {
    const items = await fetch(
        "http://localhost:1337/api/items?populate=image",
        { method: "GET"}
    );
    const itemsJson = await items.json();
    // 移除dispatch,直接更新组件state
    setItems(itemsJson.data);
}
  1. 添加空值保护:在调用slice前对items做可选链判断,避免请求未完成时的报错:
{items?.slice(0,4).map((item, i) => (
    <Item key={`${item.id}-${i}`} item={item} />
))}

错误2:SyntaxError: Cannot use import statement outside a module

核心原因

  • getItem函数中的fetch URL存在换行和空格,导致请求地址无效,返回非预期内容引发连锁解析错误。
  • 上述state更新错误导致组件渲染异常,间接触发模块解析报错。

修复步骤

  1. 修正fetch URL格式:移除URL中的换行和空格,确保参数拼写正确:
async function getItem() {
    const item = await fetch(
        // 修正参数格式,移除换行空格
        `http://localhost:1337/api/items/${itemId}?populate=image`,
        { method: "GET" }
    );
    const itemJson = await item.json();
    setItem(itemJson.data);
}
  1. 完成上述所有修复后,重启React项目,该报错通常会随主错误的修复而消失。

额外优化建议

  • 给Item组件的key使用更稳定的唯一值(比如item.id),避免item.name重复导致的渲染异常。
  • 在img标签中添加默认图片地址,避免商品信息未加载时的空白:
<img 
    alt={item?.attributes?.name || "Product image"}
    width="100%"
    height="100%"
    src={`http://localhost:1337${item?.attributes?.image?.data?.attributes?.formats?.medium?.url || "/default-product.png"}`}
    style={{ objectFit: "contain" }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:57:21