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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:27:02