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

React渲染数据库数据时触发Cannot read property 'map' of undefined错误如何解决

报错原因分析
  • 初始化状态未赋值:你使用useState()声明prodList时没有传入初始值,此时prodList的初始值为undefined。组件首次渲染时接口请求还未返回结果,代码直接执行prodList.map就会触发该报错。
  • 异步函数逻辑错误:你定义的getitems异步函数没有返回任何值,仅在内部执行了setPass(response.data)操作,所以useEffect中getitems().then()拿到的回调参数是undefined,哪怕接口请求完成,给prodList赋的值也是空,后续渲染依然会报错。另外你声明的pass状态完全冗余,没有使用必要。
修复方案
  1. 给prodList设置初始值为空数组,避免首次渲染报错
  2. 改造getitems函数,直接返回接口数据,删除多余的pass状态
  3. 可额外加可选链做兜底兼容,避免后端返回非数组格式的异常情况

修正后的代码如下:

import { useState, useEffect } from 'react';
import axios from 'axios';
// 其余组件导入(Container/ProductListToolbar等)保留原有逻辑即可

const ProductList =  () => {
  // 初始化赋值为空数组
  const [prodList, setProdList] = useState([]);

  const getitems = async () => {
    const response = await axios.get('http://localhost:3001/services');
    return response.data;
  }

  useEffect(() => {
    getitems().then(data => setProdList(data));
  }, []);

  return (
    <>
      <Container maxWidth={false}>
        <ProductListToolbar />
        <Box sx={{ pt: 3 }}>
          <Grid
            container
            spacing={3}
          >
            {/* 可选链?.做兜底兼容,更稳妥 */}
            {prodList?.map((product) => (
              <Grid
                item
                key={product.serviceID}
                lg={4}
                md={6}
                xs={12}
              >
                <ProductCard product={product} />
              </Grid>
            ))}
          </Grid>
        </Box>
      </Container>
    </>
  )
}

export default ProductList;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:45:02