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

React项目本地正常生产环境报错:TypeError: o.map is not a function

问题:React项目部署到Vercel后出现TypeError: o.map is not a function错误

本地开发环境运行正常,但部署到Vercel平台后出现报错,错误信息为:
react-dom.production.min.js:189 TypeError: o.map is not a function
对应Home.jsx第31行的map函数调用。

错误栈如下:

react-dom.production.min.js:189 TypeError: o.map is not a function
    at gd (Home.jsx:31:15)
    at xo (react-dom.production.min.js:167:137)
    at Cu (react-dom.production.min.js:197:258)
    at Es (react-dom.production.min.js:292:88)
    at bc (react-dom.production.min.js:280:389)
    at gc (react-dom.production.min.js:280:320)
    at mc (react-dom.production.min.js:280:180)
    at ac (react-dom.production.min.js:271:88)
    at ic (react-dom.production.min.js:268:429)
    at w (scheduler.production.min.js:13:203)
du @ react-dom.production.min.js:189

相关代码(Home.jsx):

import React, { useState, useEffect } from "react";
import styled from "styled-components";
import Card from "../components/Card";
import axios from "axios";
const Container = styled.div`
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
`;
const Home = ({ type }) => {
  const [Videos, setVideos] = useState([]);
  useEffect(() => {
    const fetchVideos = async () => {
      // const res = await axios.get(`http://localhost:5000/api/videos/${type}`);
      const res = await axios.get(`/videos/${type}`);
      setVideos(res.data);
      console.log(res.data);
      console.log(typeof res.data);
    };
    fetchVideos();
  }, [type]);

  return (
    <Container>
      {/* {Array.from(videos)
        ? Array.from(videos).map((video) => (
            <Card key={video._id} video={video} />
          ))
        : null} */}
      {/* {Array.from(Videos).map((video) => (
        <Card key={video._id} video={video} />
      ))} */}
      {Videos.map((video) => (
        <Card key={video._id} video={video} />
      ))}
    </Container>
  );
};

export default Home;

解决方案

核心原因

部署后API返回的res.data不是数组类型,导致调用map方法时报错。本地与生产环境的差异通常源于:

  • API路径配置错误(Vercel的API路由前缀与本地代理不一致)
  • API返回格式变化(生产环境返回包含数组的对象,而非直接返回数组)

具体修复步骤

  1. 确认API返回格式
    查看Vercel生产环境的控制台日志(或浏览器开发者工具),检查res.data的实际类型和结构,判断是对象还是数组。

  2. 修正API请求路径
    如果你的API部署在Vercel的pages/api目录下,请求路径应改为/api/videos/${type},而非/videos/${type}:

    const res = await axios.get(`/api/videos/${type}`);
    
  3. 适配响应数据结构
    若API返回的是包含数组的对象(例如{ data: [/* 视频列表 */] }),调整setVideos的逻辑:

    // 根据实际返回的字段名调整,确保最终存入Videos的是数组
    setVideos(Array.isArray(res.data) ? res.data : res.data.data || []);
    
  4. 添加数组类型校验
    在渲染时先判断Videos是否为数组,避免直接调用map:

    {Array.isArray(Videos) && Videos.map((video) => (
      <Card key={video._id} video={video} />
    ))}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:25:20