我想知道是否有辦法在用戶輸入值后幾秒鐘內呼叫 API。
此邏輯在Saga middleware使用takeLatest關鍵字獲取最新值并進行 api 呼叫的地方實作。
import { takeLatest} from 'redux-saga/effects';
function* watchTheRequest() {
const watcher = yield takeLatest('SOME_TYPE', callMySaga);
yield take(LOCATION_CHANGE);
yield cancel(watcher);
}
我正在嘗試在 React UseEffect 掛鉤中實作相同的功能。
要求是:一旦用戶停止輸入,進行 API 呼叫。
const [search, setSearch] = useState("")
useEffect(() => {
//wait for user to stop updating the search.
// call API.
}, [search])
不確定我是否需要使用以下任一方法來完成此任務
var intervalID = setInterval(alert, 1000);
setTimeout(alert, 1000);
uj5u.com熱心網友回復:
這叫做Debounce技術,你可以在這里查看
您可以嘗試使用此實作
const timeoutId = useRef();
const [searchTerm, setSearchTerm] = useState('');
const onSearchChange = (newSearchTerm) => {
// Wait for 300ms after users stop typing
// then dispatch to get the suggestions
clearTimeout(timeoutId.current);
timeoutId.current = setTimeout(() => {
if (newSearchTerm.length >= 2) {
dispatch(getSuggestions(newSearchTerm));
}
}, 300);
};
uj5u.com熱心網友回復:
這可能被稱為“去抖動”。使用 useEffect 的簡約實作:
const [search, setSearch] = useState("");
const toBeCalled = () => {
// call your API here
}
useEffect(() => {
const timer = setTimeout(toBeCalled, 1000);
return () => clearTimeout(timer);
}, [search]);
uj5u.com熱心網友回復:
如果你使用 React 18,你可以使用useDeferredValue
const [search, setSearch] = useState("")
const deferredSearch = useDeferredValue(search)
useEffect(() => {
//wait for user to stop updating the search.
// call API.
}, [deferredSearch])
......
}
查看此博客以獲取更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528298.html
標籤:反应打字稿反应式反应钩子
