在 ReactJS 功能组件中实现 Lodash 的去抖动

Implementing Lodash's debounce in a ReactJS functional component

我正在尝试使用 Lodash 的 debounce 函数消除文本输入字段更改的抖动。

import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  const onChange = debounce((e) => {
    const { value } = e.target;
    console.log('debounced value', value)
  }, 1000)

  return (

    <input type="text" onChange={ onChange } />

  )
};

上面的代码抛出以下错误:

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

Uncaught TypeError: Cannot read property 'value' of null

正确的实施方式是什么?

解决方法不是从事件中检索值,而是直接通过引用从输入中检索值。

import React, { useRef } from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  const input = useRef( null )

  const onChange = debounce(() => {
    console.log('debounced value', input.current.value)
  }, 1000)

  return (

    <input ref={ input } type="text" onChange={ onChange } />

  )
};

When to Use Refs There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Avoid using refs for anything that can be done declaratively.

Refs and the DOM

您定义的方式 Input,我假设它会在很多地方使用。所以,我会这样做:

import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  // Debounced function
  // `printValue` only cares about last state of target.value
  const printValue = debounce(value => console.log(value), 1000);

  // Event listener called on every change
  const onChange = ({ target }) => printValue(target.value);

  return <input type="text" onChange={ onChange } />;    

};