React Material-UI DataGrid填充行返回undefined问题排查
问题分析与修复方案
核心问题汇总
- 请求语法错误:
axios.get的括号未闭合,导致请求根本无法发送,list始终保持初始的undefined状态 - 初始状态无默认值:
useState初始值设为undefined,首次渲染时list?.data不存在,map执行后testrows变为undefined,而Material-UI的DataGrid要求rows必须是数组类型 - State存储冗余:没必要存储整个
AxiosResponse对象,只需要保留响应里的data数据即可 - useMemo依赖不严谨:用
list?.data作为依赖,当list为undefined时依赖判断失效,且引用类型的依赖逻辑需要更精准
修复后的完整代码
import axios from 'axios'; import { useState, useEffect, useMemo } from 'react'; import { DataGrid, GridColDef } from '@mui/x-data-grid'; // 定义水果数据类型,替代any提升类型安全性 interface Fruit { id: number; type: string; harvest: string; entryDate: string; } export default function FruitList() { // 直接存储数据数组,初始值设为空数组避免undefined问题 const [fruitList, setFruitList] = useState<Fruit[]>([]); const columns: GridColDef[] = [ { field: 'id', headerName: 'Fruit ID', type: 'number' }, { field: 'type', headerName: 'Fruit Type', type: 'string' }, { field: 'harvest', headerName: 'Harvest Date', type: 'date' }, { field: 'entryDate', headerName: 'Entry Date', type: 'date' }, ]; useEffect(() => { // 修复axios.get括号闭合问题,添加错误捕获 axios.get<Fruit[]>('http://localhost:3000/v1/fruit/') .then(result => { // 仅存储响应的data部分 setFruitList(result.data); }) .catch(err => { console.error('获取水果列表失败:', err); }); }, []); // 用useMemo缓存映射结果,依赖直接绑定fruitList const testrows = useMemo(() => { // 因fruitList初始为空数组,map不会出现undefined问题 return fruitList.map(element => ({ id: element.id, type: element.type, // 后端返回字符串日期时需转为Date对象,根据实际情况调整 harvest: new Date(element.harvest), entryDate: new Date(element.entryDate) })); }, [fruitList]); console.log("test: ", testrows); return ( <div style={{ height: 400, width: '100%' }}> <DataGrid rows={testrows} columns={columns} // 可选:添加loading状态,请求未完成时显示加载动画 loading={fruitList.length === 0} /> </div> ); }
关键修复点说明
- 修正请求语法:补全
axios.get的闭合括号,确保请求能正常发送 - 设置State初始值:将
fruitList初始化为空数组[],首次渲染时map返回空数组,符合DataGrid对rows的类型要求 - 优化State存储:仅存储响应的
data部分,简化状态管理逻辑 - 完善类型定义:添加
Fruit接口替代any,避免类型模糊导致的潜在问题 - 添加错误处理:通过
catch捕获请求异常,便于排查接口调用问题 - 调整useMemo依赖:直接用
fruitList作为依赖,确保数据更新时能重新计算testrows - 日期格式适配:若后端返回字符串格式日期,转为
Date对象才能让DataGrid的日期列正常渲染
内容的提问来源于stack exchange,提问作者RuntimeError
相关产品推荐
相关产品推荐

