[英]React / TS: Throttle function but also set state
我有一個 React 功能組件。 有一個input
字段,其value
是使用useState
設置的。 我有一個簡單的標准function throttle(callback: Function, delay = 1000)
要求:
onChange
事件處理程序設置搜索詞(狀態)。我可以做一個,但不能兩個都做。 一邊用頭撞牆。
我究竟做錯了什么?
謝謝你。
(僅供參考,我對去抖動不感興趣。)
使用useRef
存儲 shouldWait 的值應該是shouldWait
的方式。 此外,可以在throttle
useCallback
上使用 useCallback 來記憶它。
import React, { ChangeEvent, useState, useMemo, useRef, useCallback } from "react";
/*
Requirements:
1. Set search term (state),
2. Throttle the callback (search()) function call.
There are two functions that should be interesting, both onChange handlers:
* handleOnChange (Does not satisfy Requirement 2)
* throttledOnChangeHandler (Does not satisfy Requirement 1)
*/
export const Searchbox: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const shouldWait = useRef<boolean>(false);
const throttle = useCallback((callback: Function, delay = 1000, ...args: any[]) => {
if (shouldWait.current) return;
callback(...args);
shouldWait.current = true;
setTimeout(() => {
shouldWait.current = false;
}, delay);
}, []);
function search() {
console.log(new Date().getSeconds())
console.log("Searching term:", searchTerm);
}
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
throttle(search);
setSearchTerm(e.target.value);
};
return (
<div>
<h1>Search!</h1>
<input
type="text"
placeholder="Blah!"
value={searchTerm}
onChange={handleOnChange}
/>
</div>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.