React类组件搜索函数优化:如何提升9000条数据的搜索速度
React类组件搜索性能优化方案
针对你9000条数据的搜索卡顿问题,给你几个实用的优化方向:
1. 预处理数据,缓存小写名称
每次筛选都重复调用item.name.toLowerCase()是没必要的,提前把所有数据的名称转成小写缓存起来,能减少大量重复计算:
// 在组件初始化或者bigData更新时执行 componentDidMount() { this.processedData = this.state.bigData.map(item => ({ ...item, lowercaseName: item.name.toLowerCase() })); } // 如果bigData会动态更新,同步更新processedData componentDidUpdate(prevProps, prevState) { if (prevState.bigData !== this.state.bigData) { this.processedData = this.state.bigData.map(item => ({ ...item, lowercaseName: item.name.toLowerCase() })); } }
2. 合并遍历逻辑,减少数组遍历次数
你现在的代码要遍历三次数组(精确匹配→全词匹配→单词匹配),改成一次遍历完成所有判断,直接找到优先级最高的匹配结果:
search = (event) => { const searchTerm = event.target.value.toLowerCase(); this.setState({ searchTerm }); if (searchTerm.length < 2) { this.setState({ matches: [] }); return; } if (this.timer) clearTimeout(this.timer); this.timer = setTimeout(() => { const searchWords = searchTerm.split(' '); let exactMatches = []; let allWordMatches = []; let singleWordMatches = []; // 一次遍历完成所有匹配判断 for (const item of this.processedData) { const { lowercaseName } = item; // 优先判断精确匹配 if (lowercaseName === searchTerm) { exactMatches.push(item); continue; } // 判断全词包含 const hasAllWords = searchWords.every(word => lowercaseName.includes(word)); if (hasAllWords) { allWordMatches.push(item); continue; } // 判断单词包含 const hasAnyWord = searchWords.some(word => lowercaseName.includes(word)); if (hasAnyWord) { singleWordMatches.push(item); } } // 按优先级返回结果 let result = []; if (exactMatches.length > 0) { result = exactMatches; } else if (allWordMatches.length > 0) { result = allWordMatches; } else { result = singleWordMatches; } this.setState({ matches: result }); this.timer = null; }, 600); // 可适当缩短防抖时间,提升响应感 }
3. 优化防抖逻辑,避免内存泄漏
在组件卸载时清理定时器,防止内存泄漏:
componentWillUnmount() { if (this.timer) clearTimeout(this.timer); }
4. 优化渲染性能
如果搜索结果通过子组件渲染,给子组件加上React.memo避免不必要的重渲染:
const ResultItem = React.memo(({ item }) => { // 渲染逻辑 });
这些优化能大幅减少计算量,一次遍历替代三次,加上预处理的缓存,应该能解决卡顿问题。
内容的提问来源于stack exchange,提问作者Hejhejhej123
相关产品推荐
相关产品推荐

