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

react-table表格搜索时如何对数组类型字段colors进行过滤

问题原因

崩溃的核心原因是colors为数组类型,JavaScript 中数组原型上没有toLowerCase()方法,直接调用该方法会抛出类型错误导致程序崩溃。

修复方案
  • 提前将输入的搜索值转为小写,避免重复执行转换逻辑
  • 对colors字段增加类型校验,确认字段存在且为数组类型后再执行匹配逻辑
  • 遍历colors数组的每一项,逐个转为小写后判断是否包含搜索值

修复后的完整代码如下:

// 搜索值提前转小写,减少重复转换开销
const lowerCaseValue = value.toLowerCase()

function search(rows: any[]) {
    return rows.filter(
      (row) => 
      row.name?.toLowerCase().indexOf(lowerCaseValue) > -1 ||
      row.id?.toLowerCase().indexOf(lowerCaseValue) > -1 ||
      row.label?.toLowerCase().indexOf(lowerCaseValue) > -1 ||
      // 处理colors数组字段匹配逻辑
      Array.isArray(row.colors) && row.colors.some(color => 
        color?.toLowerCase().indexOf(lowerCaseValue) > -1
      )
    )
};
优化说明
  1. 用可选链?.避免字段为undefined/null时抛出类型错误
  2. 用Array.isArray()先校验colors的类型,只有是数组时才执行后续匹配逻辑
  3. 用数组的some()方法遍历匹配,只要数组中有一项符合条件就返回真,匹配到第一个符合项就会停止遍历,性能更优

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:24:03