如何在react-router v6.4.3中取消搜索查询



我有一个搜索输入,更新查询参数,并在每次onChange事件时触发react-router加载器中特定路由的API调用。我如何防止在每次击键时调用API并实现类似debounce效果的东西(当用户没有输入1000ms时,然后调用API或更新查询参数)。注意:我知道有一个debounce hook和逻辑,但我感兴趣的是是否有可能实现仅用react-router。

组件,其中我有更新查询参数逻辑:

const [searchParams, setSearchParams] = useSearchParams();
const countryQuery = searchParams.get("country") || "";
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
setSearchParams(
{ country: event.target.value }
);
};

装载机:

export const loader = async ({ request }: LoaderFunctionArgs) => {
const url = new URL(request.url);
const countryQuery = url.searchParams.get("country") || "";
const countries = getCountries(countryQuery);
return countries;
};

我希望避免不必要的API调用。

您可以尝试使用debounce from lodash

import { debounce, filter, get, join, map } from 'lodash';

使用setter

的简单版本
const debouncedOnChange = useCallback(
debounce((event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
setSearchParams(
{ country: event.target.value }
);
}, 300), []);

如果需要在句柄搜索中引用其他变量,可以useRef

const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
setSearchParams(
{ country: event.target.value }
);
};
const searchRef = useRef(handleOnChange);
searchRef.current = handleOnChange;
const debouncedOnChange = useCallback(debounce(searchRef.current, 300), []);

你可以尝试用debouncedOnChange代替handleOnChange

希望对你有所帮助

最新更新