目前,我有一个复选框列表,onChange 将向服务器发出请求以返回一些数据。但是,只有当用户在一段时间后停止选择多复选框时,我才使用 lodash debounce 尝试发出请求。
目前,它会阻止立即分派,但会在达到去抖动时间后分派,而不是在用户停止与复选框交互时分派。有人能告诉我我将如何实现这一目标或我哪里出错了吗?
谢谢!
import React, { useContext, useState, useEffect } from 'react';
import { Context } from '../../pages/search-and-results/search-and-results.js';
import debounce from 'lodash.debounce';
const FilterCheckbox = ({ name, value }) => {
const checkboxContext = useContext(Context);
const [checked, setChecked] = useState(false);
const debounceCheckboxSelection = debounce(dispatchCheckbox, 2000);
function dispatchCheckbox(type, value) {
checkboxContext.dispatch({
type: type,
payload: { value }
});
}
return (
<Label>
<FilterInput
type="checkbox"
name={name}
onChange={() => {
if (checked) {
debounceCheckboxSelection('REMOVE_SELECTED_PROPERTY_TYPE', value);
setChecked(false);
return;
}
debounceCheckboxSelection('SET_SELECTED_PROPERTY_TYPE', value);
setChecked(true);
}}
checked={checked}
/>
{name}
</Label>
);
};
export default FilterCheckbox;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>