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 ) ) };
优化说明
- 用可选链
?.避免字段为undefined/null时抛出类型错误 - 用
Array.isArray()先校验colors的类型,只有是数组时才执行后续匹配逻辑 - 用数组的
some()方法遍历匹配,只要数组中有一项符合条件就返回真,匹配到第一个符合项就会停止遍历,性能更优
内容的提问来源于stack exchange,提问作者mike23
相关产品推荐
相关产品推荐

