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

React项目Joke.map is not a function错误及API返回异常求助

Vite+React项目中Joke.map is not a function错误及API请求异常解决

问题说明

在Vite+React项目中调用Joke.map()时触发Joke.map is not a function错误;通过axios请求/api/jokes接口,控制台无预期响应数据;使用Postman请求该接口时,返回的是Vite的HTML页面而非笑话数据。

相关代码

import { useEffect, useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import axios from 'axios'

function App() {
  const [Joke,setJokes]=useState([])
  
  
  useEffect(()=>{
    
    axios.get(' /api/jokes')
          .then((response)=>{
            console.log(response)
              setJokes(response.data);
           
          })
          .catch((error=>{
            console.log(error)
          }))
  })

  return (
    <>
      <h1>Omkar Mundhe</h1>
      <p>JOKES:{Joke.length}</p>
      {
        Joke.map((joke,index)=>{
          <div key={joke.id}>
            <h3>{joke.setup}</h3>
            <p>{joke.punchline}</p>
          </div>
        })
      }
    </>
  )
}

Postman返回的HTML内容

<!doctype html>
<html lang="en">

<head>
    <script type="module">
        import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
    </script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
</head>

<body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx?t=1719029620018"></script>
</body>

</html>

控制台情况

请求/api/jokes返回的是Vite的HTML页面,导致response.data是HTML字符串而非数组,进而调用map()时触发错误。

解决方案

1. 配置Vite代理解决API请求转发问题

因为Vite开发服务器未配置代理,/api/jokes请求被当成前端静态资源/路由处理,返回了入口HTML页面。需要在项目根目录的vite.config.js中添加代理配置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: '你的API实际地址(例如http://localhost:3000)',
        changeOrigin: true,
        // 若API接口本身不带/api前缀,可添加rewrite规则移除前缀
        // rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

配置完成后重启Vite开发服务器,/api/jokes请求会被转发到目标API服务器,获取正确的笑话数据。

2. 修复useEffect重复请求问题

当前useEffect没有依赖数组,会导致组件每次渲染都重复发起请求,需添加空依赖数组,让请求仅在组件挂载时执行一次:

useEffect(()=>{
  axios.get('/api/jokes') // 注意去掉地址前的空格
    .then((response)=>{
      console.log(response)
      setJokes(response.data);
    })
    .catch((error=>{
      console.log(error)
    }))
}, [])

3. 修复map函数无返回值问题

当前map回调中的JSX没有返回,导致页面无法渲染笑话内容,需补充返回逻辑:

{
  Joke.map((joke, index) => {
    return (
      <div key={joke.id}>
        <h3>{joke.setup}</h3>
        <p>{joke.punchline}</p>
      </div>
    )
  })
}
// 或使用箭头函数隐式返回简化代码
{
  Joke.map((joke, index) => (
    <div key={joke.id}>
      <h3>{joke.setup}</h3>
      <p>{joke.punchline}</p>
    </div>
  ))
}

4. 优化状态变量命名

状态变量Joke存储的是数组,建议命名为jokes(小写复数),符合JS命名规范,避免混淆:

const [jokes, setJokes] = useState([])
// 对应修改后续代码:
// <p>JOKES:{jokes.length}</p>
// jokes.map(...)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:17:25