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

React页面跳转时报TypeError: Cannot read 'map' of undefined如何解决

问题根因
  • 即使isSuccess状态为真,也可能出现接口返回结构不符合预期、useQuery缓存读取时序异常、组件重渲染时序差的情况,导致你直接访问的res.data.Result为undefined,调用map方法就会抛出对应错误。
  • 页面跳转时组件优先读取useQuery的缓存数据,这个阶段如果缓存数据结构异常就会触发报错;刷新页面时会重新发起完整请求,数据返回后才执行渲染逻辑,因此不会报错。
修复方案

1. 增加字段兜底判断(最快生效)

访问数组前添加可选链和空值兜底,即使Result字段为空,也会默认返回空数组,不会触发调用方法的报错:

// 把原有渲染逻辑中的res.data.Result.map替换为以下写法
{isSuccess &&
  (res?.data?.Result ?? []).map((product) => (
    <Col key={product.ID} md="4" sm="4">
      {/* 原有产品卡片渲染逻辑不变 */}
    </Col>
  ))
}

2. 调整useQuery缓存策略

可以根据业务需求设置缓存有效期,避免读取过旧的异常缓存数据:

const {
    isLoading,
    isError,
    error,
    data: res,
    isSuccess,
  } = useQuery("product", () => Axios.get(`/Product/AllProduct`), {
    staleTime: 1000 * 60 * 5, // 5分钟内数据视为有效,不会重复发起请求
    cacheTime: 1000 * 60 * 10 // 10分钟后自动清理缓存
  });

3. 增加请求返回结构校验

在请求回调中提前校验结构是否符合预期,避免异常结构存入缓存:

const {
    isLoading,
    isError,
    error,
    data: res,
    isSuccess,
  } = useQuery("product", async () => {
    const response = await Axios.get(`/Product/AllProduct`);
    // 校验返回的产品列表是否为数组
    if (!response?.data?.Result || !Array.isArray(response.data.Result)) {
      throw new Error("产品数据格式异常");
    }
    return response;
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:12:03