【发布时间】:2020-09-24 12:01:17
【问题描述】:
目前,我有一个复选框列表,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>
【问题讨论】:
标签: reactjs debounce debouncing