MUI GridToolbar日期筛选失效,筛选后返回空数组求助
MUI GridToolbar日期字段筛选失效问题解决
我使用MUI GridToolbar筛选表格中的日期字段时,前端格式化展示正常,但筛选功能返回空数组,相关代码及数据如下:
后端返回的原始数据
[ { "_id": "6434ffefa330ecceac9e3dbb", "email": { "_id": "642cee2137f8757b475d1c87", "firstName": "test1", "lastName": "test1", "email": "test1@gmail.com" }, "category": "faculty", "affiliation": "ppsc_faculty", "createdAt": "2023-12-11T06:36:31.623Z", "updatedAt": "2023-12-11T06:36:31.623Z", "__v": 0 }, { "_id": "6434ec9b42067a96c612b819", "email": { "_id": "642cee2137f8757b475d1c87", "firstName": "test1", "lastName": "test1", "email": "test1@gmail.com" }, "category": "faculty", "affiliation": "ppsc_faculty", "createdAt": "2023-12-11T05:14:03.525Z", "updatedAt": "2023-12-11T05:14:03.525Z", "__v": 0 } ]
前端日期格式化代码
{ field: 'createdAt', headerName: 'Date', width: 300, filterable: true, renderCell: (params) => { const dateString = params.row.createdAt; const date = new Date(dateString); const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); return `${day}-${month}-${year}`; }, }
后端API代码
export const GetRecentSurvey = async (req,res) =>{ const affiliate = req.query.affiliate try { let results if(affiliate){ results = await Completed.find({affiliation: affiliate}) .populate({path: "email", select: "firstName lastName email"}) .sort({createdAt: 'desc'}) } else{ results = await Completed.find() } res.status(200).json(results) } catch (error) { res.status(error).json(error) } }
问题原因
- 前端筛选逻辑不匹配:MUI DataGrid默认基于字段原始值筛选,你前端展示的是
日-月-年格式字符串,但实际筛选时用的是后端返回的ISO格式日期(如2023-12-11T06:36:31.623Z),两者格式不一致导致匹配失败。 - 后端未处理日期筛选:当前API仅支持
affiliate参数筛选,没有接收和处理日期相关的筛选条件,即使前端传了日期参数,后端也不会执行对应查询。
解决方法
方案1:前端本地筛选(小数据量场景)
修改列配置,让筛选基于格式化后的日期值,通过valueGetter统一处理展示和筛选的数据源:
{ field: 'createdAt', headerName: 'Date', width: 300, filterable: true, valueGetter: (params) => { const dateString = params.row.createdAt; const date = new Date(dateString); const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); return `${day}-${month}-${year}`; }, renderCell: (params) => params.value, }
方案2:后端支持日期筛选(大数据量场景)
修改API,添加日期范围筛选逻辑,接收startDate和endDate参数并在MongoDB查询中应用:
export const GetRecentSurvey = async (req,res) =>{ const { affiliate, startDate, endDate } = req.query try { let query = {}; // 处理 affiliate 筛选 if(affiliate){ query.affiliation = affiliate; } // 处理日期范围筛选 if(startDate && endDate){ query.createdAt = { $gte: new Date(startDate), $lte: new Date(endDate) }; } else if(startDate){ query.createdAt = { $gte: new Date(startDate) }; } else if(endDate){ query.createdAt = { $lte: new Date(endDate) }; } const results = await Completed.find(query) .populate({path: "email", select: "firstName lastName email"}) .sort({createdAt: 'desc'}); res.status(200).json(results) } catch (error) { res.status(500).json({message: error.message}); } }
同时前端需要通过onFilterModelChange事件捕获筛选条件,将日期参数传递给后端,也可以给日期列配置MUI DatePicker组件作为筛选器,提升用户体验。
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

