我正在使用 React(类组件)并创建了一个搜索功能。它在搜索我想要的东西方面做得很好,但有时它会变得缓慢而无法使用。使用 onChange 在输入更改时触发搜索组件。过滤后的“bigData”状态是一个始终包含 9000 个对象的数组,每个对象由三个属性组成。
正如你所看到的,我尝试创建节流阀,它产生了巨大的差异,但有时仍然会很慢。由于各种原因,我真的不想要搜索按钮,所以这不是一个选项。
知道如何加快搜索功能吗?
search = (event) => {
const searchTerm = event.target.value.toLowerCase();
this.setState({ searchTerm: searchTerm });
if(searchTerm.length < 2) {
return;
}
// Clear any existing timer
if(this.timer) {
clearTimeout(this.timer);
}
// Set a new timer to delay the search by 800ms
this.timer = setTimeout(() => {
const exactMatchesName = this.state.bigData.filter(item => item.name.toLowerCase() === searchTerm);
if(exactMatchesName.length > 0) {
this.setState({ matches: exactMatchesName })
this.timer = null;
return;
}
const allWords = searchTerm.split(' ');
const containsAllWordsName = this.state.bigData.filter(item => allWords.every(word => item.name.toLowerCase().includes(word)));
if(containsAllWordsName.length > 0) {
this.setState({ matches: containsAllWordsName })
this.timer = null;
return;
}
const individualWordsName = searchTerm.split(' ');
const oneWordMatchesName = this.state.bigData.filter(item =>
individualWordsName.some(word => item.name.toLowerCase().includes(word))
);
this.setState({ matches: oneWordMatchesName })
this.timer = null;
}, 800);
}
您可以使用带有快捷方式的单个循环来获得更高优先级的搜索结果。
const
searchTerm = event.target.value.toLowerCase();
splitted = searchTerm.split(' '),
result = [[], [], []];
let index = 2;
for (const item of bigData) {
const name = item.name.toLowerString();
if (name === searchTerm) {
index = 0;
result[index].push(item);
}
if (index === 0) continue;
if (splitted.every(w => name.includes(w)) {
index = 1;
result[index].push(item);
}
if (index === 1) continue;
if (splitted.some(w => name.includes(w)) {
result[2].push(item);
}
}
// finally take result[index]