我想知道在用户输入这些值之后,是否有一种在几秒钟内调用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钩子中实现同样的功能。
的要求是:一旦用户停止输入,就进行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);发布于 2022-11-06 16:38:42
这很可能叫做“脱欧”。使用useEffect进行极简的实现:
const [search, setSearch] = useState("");
const toBeCalled = () => {
// call your API here
}
useEffect(() => {
const timer = setTimeout(toBeCalled, 1000);
return () => clearTimeout(timer);
}, [search]);发布于 2022-11-06 16:43:23
这叫做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);
};发布于 2022-11-06 17:04:08
如果您正在使用React 18,则可以使用useDeferredValue。
const [search, setSearch] = useState("")
const deferredSearch = useDeferredValue(search)
useEffect(() => {
//wait for user to stop updating the search.
// call API.
}, [deferredSearch])
......}
检查此博客以获取更多信息
https://stackoverflow.com/questions/74337727
复制相似问题