目前,我有一个复选框列表,onChange 将向服务器发出请求以返回一些数据。但是,我使用 lodash debounce 仅在用户在一定时间后停止选择多复选框时尝试发出请求。
目前,它会阻止立即分派(dispatch),但会在达到去抖动时间后而不是在用户停止与复选框交互时进行分派(dispatch)。有人可以告诉我如何实现这一目标或我哪里出错了吗?
谢谢!
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>
最佳答案
每次重新渲染时都会创建您的去抖动函数,以修复它:
您可以使用 useRef
它返回一个 ref 对象,该对象将在组件的整个生命周期内持续存在:
const debounceCheckboxSelection = useRef(
debounce(dispatchCheckbox, 2000);
)
并使用
debounceCheckboxSelection.current
访问其初始值:<FilterInput
type="checkbox"
name={name}
onChange={() => {
if (checked) {
debounceCheckboxSelection.current('REMOVE_SELECTED_PROPERTY_TYPE', value);
setChecked(false);
return;
}
debounceCheckboxSelection.current('SET_SELECTED_PROPERTY_TYPE', value);
setChecked(true);
}}
checked={checked}
/>
或者您可以使用
useCallback
将返回回调的内存版本,该回调仅在其任何依赖项更改时才会更改:const debounceCheckboxSelection = useCallback(
() => debounce(dispatchCheckbox, 2000), []
)
关于reactjs - Lodash debounce 不会像预期的那样阻止调度 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62212641/