【问题标题】:What is the best way to add _.throttle on a react element?在反应元素上添加 _.throttle 的最佳方法是什么?
【发布时间】:2022-01-18 08:25:08
【问题描述】:

我正在努力找出在 onChange 元素(例如输入)上使用 _.throttle 的最佳方式。显然它与 _.debounce 的工作方式不同。

// This works as expected! Replacing 'debounce' with 'throttle' does not work though.
<Input onChange={_.debounce(onInputChange, 1000)} />
// This does not work. It work as if the wait-time is set to 0
const page = () => {
    const [input, setInput] = React.useState('')

    const onInputChange = () => {
        console.log('Hi!')
    }

return(
    <Input onChange={_.throttle(onInputChange, 1000}/>
)}

.

文档说明使用 _.throttle 的方法是确保您只调用该函数一次

// WRONG
$(window).on('scroll', function() {
   _.debounce(doSomething, 300); 
});

// RIGHT
$(window).on('scroll', _.debounce(doSomething, 200));

谢谢!什么都有帮助

【问题讨论】:

    标签: javascript reactjs lodash


    【解决方案1】:

    为功能组件定义一次函数并确保每次渲染都不会重新声明/重置它的简单方法是使用没有依赖关系的useCallback。您的 debounce 可能看起来 可以正常工作,但从技术上讲,debounce 函数会执行每个渲染,因此它的功能并不完全符合您的想法。因此,对于油门、去抖动和任何其他类似功能,您可以执行以下操作:

    function App() {
        const [val, setVal] = useState('');
        const onChangeDebounced = useCallback(_.debounce(setVal, 250), []);
        const onChange = e => onChangeDebounced(e.target.value);
    
        return (
            <input type='text' value={val} onChange={onChange} />
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2014-05-12
      • 2013-08-21
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多