我已经在我的应用程序中实现了一个过滤下拉列表,但是,由于该下拉列表中的填充数据是一个巨大的数据集,因此被分页,因此在每次输入字符时都会触发API调用,这不是很正常对于性能,是否有解决此问题的已知方法? 我正在使用react,因此,如果有任何特定于React的方法或香草js方法适用于我的情况。
答案 0 :(得分:1)
您可以使用反跳功能,例如我用来对一个调整大小事件进行反跳的功能,但是它在您的文本输入更改事件上也将起作用。
/**
* @description Postpones executing a callback function by a specified time until all the callback's events, occurring in rapid succession, have ended.
*
* @param {number} delay - The time in milliseconds to postpone the callback.
* @param {Function} callback - The event's callback function.
* @return {Function}
* @public
* @function
*
* @example
*
* const resizeHandler = (event) => console.log(event);
* window.addEventListener("resize", debounce(200, resizeHandler));
*
*/
const debounce = (delay, callback) => {
let timer;
return (...args) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
callback(...args);
timer = null;
}, delay);
};
};
[EDIT] 对于完整的一对,以防万一有人觉得某天有用,这是我的调节功能。
/**
* @description Delays the frequency of a callback function by a specified time.
*
* @param {number} delay - The time in milliseconds to delay the callback frequency.
* @param {Function} callback - The event's callback function.
* @return (Function)
* @public
* @function
*
* @example
*
* const mouseMoveHandler = (event) => console.log(event);
* document.body.addEventListener("mousemove", throttle(200, mouseMoveHandler));
*
*/
export const throttle = (delay, callback) => {
let previousTime = 0;
return (...args) => {
const currentTime = new Date().getTime();
if (currentTime - previousTime > delay) {
previousTime = currentTime;
return callback(...args);
}
};
};