mui-datatables使用Autocomplete作为自定义过滤器的报错及适配问题
问题1:Autocomplete组件崩溃报错
报错根因
- Autocomplete的
options属性在数据未完成加载/异常场景下为undefined,不是预期的数组类型,访问options.length直接触发类型错误 - 代码中
defaultValue写死读取filterList[5],如果当前列的索引不是5,filterList[5]为undefined,访问长度也会触发异常
修复方案
给参数加兜底逻辑,同时用传入的动态index替代写死的列索引,修复后代码如下:
{ name: "marca", label: "Marca", options: { filter: true, sort: false, filterType: "custom", sortThirdClickReset: true, customFilterListOptions: { render: (v) => `Marca: ${v.label}`, }, filterOptions: { display: (filterList, onChange, index, column) => { return ( <Autocomplete disableClearable getOptionLabel={(status) => status.marca} options={info.filters.marcas || []} // 兜底空数组,避免undefined noOptionsText={"No se encontraron resultados"} defaultValue={ // 用动态index,同时加可选链兜底判断 filterList[index]?.length > 0 ? info.filters.marcas.find(item => item.id === filterList[index][0]) || { marca: "Todos" } : { marca: "Todos" } } onChange={(event, value) => { // 直接存选项ID,适配接口参数要求 onChange([value.id], index, column) }} renderInput={(params) => ( <TextFieldMaterial {...params} fullWidth margin="normal" label="Marcas" InputLabelProps={{ shrink: true, }} /> )} /> ) }, }, }, },
问题2:接口参数需要传ID而非名称
实现逻辑
MUI-Datatables的自定义过滤器支持自定义存储值,按以下步骤配置即可:
- 确保你的选项数组
info.filters.marcas同时包含id和marca字段,示例结构:[{id:1, marca:'FORD'}, {id:2, marca:'BMW'}] - Autocomplete的
onChange回调中,给MUI-Datatables的onChange方法传递选项的id而非名称,如上面修复代码的写法 - 已选过滤器列表需要展示名称的话,修改
customFilterListOptions.render方法,根据存储的ID匹配对应的名称展示即可 - 最后在你对接服务器请求的逻辑中,拿到的
marca过滤值就是ID,直接拼接成&marca=1的格式即可
内容的提问来源于stack exchange,提问作者Gianfranco Depaoli Gampel
相关产品推荐
相关产品推荐

