Lodash 去抖动并没有像预期的那样阻止调度 onChange [英] Lodash debounce isn't preventing dispatch as expected onChange
问题描述
目前,我有一个复选框列表,onChange 将向服务器发出请求以返回一些数据.但是,只有当用户在一段时间后停止选择多复选框时,我才使用 lodash debounce 尝试发出请求.
Currently, I have a list of checkboxes that onChange will make a request to the server to return some data. However, I am using lodash debounce to try and make a request only when the user has stopped selecting the multi-checkbox after a certain amount of time.
目前,它会阻止立即分派,但会在达到去抖动时间后分派,而不是在用户停止与复选框交互时分派.有人能告诉我我将如何实现这一目标或我哪里出错了吗?
Currently, it prevents dispatching straight away but will dispatch after the debounce time has met rather when the user has stopped interacting with the checkboxes. Can someone tell me how I would achieve this or where I am going wrong?
谢谢!
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>
推荐答案
每次重新渲染时都会创建去抖动函数,以修复它:
Your debounced function is getting created at each re-render, to fix it:
您可以使用 useRef
返回将在组件的整个生命周期内持续存在的 ref 对象:
You can use useRef
which returns a ref object which will persist for the full lifetime of the component:
const debounceCheckboxSelection = useRef(
debounce(dispatchCheckbox, 2000);
)
并使用 debounceCheckboxSelection.current
访问其初始值:
and access its initial value with 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
返回回调的记忆版本,该版本仅在其任何依赖项更改时才会更改:
Or you can use useCallback
will returns a memoized version of the callback that only changes when any of its dependencies change:
const debounceCheckboxSelection = useCallback(
() => debounce(dispatchCheckbox, 2000), []
)
这篇关于Lodash 去抖动并没有像预期的那样阻止调度 onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!