React Native:使用 lodash 去抖动 [英] React Native: Using lodash debounce
问题描述
我正在研究 React Native 和 lodash 的去抖动.
I'm playing around with React Native and lodash's debounce.
使用下面的代码只会让它像延迟一样工作,而不是去抖动.
Using the following code only make it work like a delay and not a debounce.
<Input
onChangeText={(text) => {
_.debounce(()=> console.log("debouncing"), 2000)()
}
/>
如果我输入像foo"这样的输入,我希望控制台只记录一次去抖动.现在它记录了 3 次去抖动".
I want the console to log debounce only once if I enter an input like "foo". Right now it logs "debounce" 3 times.
推荐答案
2019: 使用 'useCallback' react hook
在尝试了许多不同的方法后,我发现使用useCallback"是解决多次调用问题最简单、最有效的方法.
2019: Use the 'useCallback' react hook
After trying many different approaches, I found using 'useCallback' to be the simplest and most efficient at solving the multiple calls problem.
根据 Hooks API 文档,useCallback 返回一个记忆版本仅在依赖项之一发生更改时才会更改的回调."
As per the Hooks API documentation, "useCallback returns a memorized version of the callback that only changes if one of the dependencies has changed."
传递一个空数组作为依赖确保回调只被调用一次.这是一个简单的实现.
Passing an empty array as a dependency makes sure the callback is called only once. Here's a simple implementation.
import React, { useCallback } from "react";
import { debounce } from "lodash";
const handler = useCallback(debounce(someFunction, 2000), []);
const onChange = (event) => {
// perform any event related action here
handler();
};
希望这有帮助!
这篇关于React Native:使用 lodash 去抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!