Lodash 去抖动并没有像预期的那样阻止调度 onChange

IT技术 reactjs debounce debouncing
2021-04-30 22:12: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>

1个回答

每次重新渲染时都会创建您的去抖动函数,以修复它:

您可以使用useRefwhich 返回一个 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}
/>

或者您可以使用useCallbackwill 返回回调的记忆版本,该版本仅在其任何依赖项更改时才会更改:

const debounceCheckboxSelection = useCallback(
  () => debounce(dispatchCheckbox, 2000), []
)