Filter 10k over Object is lagging



Api以{firstName:'john',lastName:'Cena'}的形式返回超过10k个对象。在我的父React组件中,我正在对挂载的组件进行API调用,并将该对象传递给子组件。

在子组件中,当用户键入时,它是滞后的。我尝试使用callback方法,但问题仍然存在。

父组件

const Filters = ({validation}: any) => {

const [EmployeeList, setEmployeeList] = useState<any[]>([]);
useEffect(() => {
//get and set
},[])
return (
<>
<Staff EmployeeList={EmployeeList}/>
</>
)
}

的子组件

const onChange = useCallback(
(e: any) => {
const userInput = e.currentTarget.value
if(staffList){
setFilteredSuggestions(staffList.filter(
staff =>
staff.firstName.toLowerCase().indexOf(userInput.toLowerCase()) > -1 
))
}
setUserInput(e.currentTarget.value)
},
[userInput]
)

一个简单的解决方案是使用for循环而不是filter(您可以使用filter并为前20个正数之后的所有元素返回false,但它不会有效)。

不是

setFilteredSuggestions(staffList.filter(
staff => staff.firstName.toLowerCase().indexOf(userInput.toLowerCase()) > -1 || staff.lastName.toLowerCase().indexOf(userInput.toLowerCase()) > -1
))

你可以做

const input = userInput.toLowerCase() // moved this out to do toLowerCase() only 1 time instead of 20k
const filtered = []
for (const staff of staffList) {
if (staff.firstName.toLowerCase().indexOf(input) > -1 || staff.lastName.toLowerCase().indexOf(input) > -1) {
filtered.push(staff)
if (filtered.length >= 20) {
break
}
}
}
setFilteredSuggestions(filtered)

最新更新