【问题标题】:Implementing Lodash's debounce in a ReactJS functional component在 ReactJS 功能组件中实现 Lodash 的 debounce
【发布时间】:2020-12-19 05:53:54
【问题描述】:

我正在尝试使用 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 } />

  )
};

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

警告:出于性能原因,此合成事件会被重复使用。如果您看到这一点,则表示您正在访问已发布/无效合成事件上的属性目标。这设置为空。如果您必须保留原始合成事件,请使用 event.persist()。

未捕获的类型错误:无法读取 null 的属性“值”

什么是正确的实现方式?

【问题讨论】:

标签: javascript reactjs lodash debouncing


【解决方案1】:

何时使用 refs 有几个很好的 refs 用例:

  • 管理焦点、文本选择或媒体播放。
  • 触发命令式动画。
  • 与第三方 DOM 库集成。

避免将 refs 用于任何可以以声明方式完成的事情。

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 } />;    

};

【讨论】:

  • 谢谢。将字符串 event.target.value 而不是整个 event 传递给 debounce 确实是这样。 react@^16.12.0"@chakra-ui/react": "^1.0.0"
【解决方案2】:

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

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 } />

  )
};

【讨论】:

  • 这里不需要使用 ref。
  • 那么如何在不使用状态的情况下检索值呢?如果有更好的方法,我将不胜感激。
猜你喜欢
  • 2019-09-01
  • 2019-07-26
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
相关资源
最近更新 更多