我在玩React Native和lodash的Debust.
使用下面的代码只会让它像延迟一样工作,而不是去抖动。
<Input
onChangeText={(text) => {
_.debounce(()=> console.log("debouncing"), 2000)()
}
/>如果我输入像"foo“这样的输入,我希望控制台只记录一次去抖动。现在它记录了3次“去抖动”。
发布于 2019-10-29 00:35:45
2019:使用'useCallback‘react钩子
在尝试了许多不同的方法后,我发现使用'useCallback‘在解决多个呼叫问题时是最简单和最有效的。
根据Hooks API documentation,"useCallback返回一个记忆过的回调版本,只有当其中一个依赖项发生变化时才会发生变化。“
将空数组作为依赖项传递可确保回调仅被调用一次。下面是一个简单的实现。
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();
};希望这能有所帮助!
发布于 2016-12-19 12:53:58
Debounce函数应该在render方法之外的某个地方定义,因为每次调用它时,它都必须引用该函数的同一实例,而不是创建一个新实例,就像现在将它放在onChangeText处理函数中一样。
最常见的定义去反跳函数的地方就在组件的对象上。下面是一个例子:
class MyComponent extends React.Component {
constructor() {
this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000);
}
onChangeText(text) {
console.log("debouncing");
}
render() {
return <Input onChangeText={this.onChangeTextDelayed} />
}
}发布于 2021-05-10 02:03:10
更新至2021年
正如其他答案所述,必须创建一次去反跳函数引用,并通过调用相同的引用来声明相关函数(即我的示例中的changeTextDebounced )。对@George Borunov的回答稍作改动就可以解决这个问题。
class SomeClassComponent extends React.Component {
componentDidMount = () => {
this.changeTextDebouncer = _.debounce(this.changeTextDebounced, 500);
}
changeTextDebounced = (text) => {
console.log("debounced");
}
render = () => {
return <Input onChangeText={this.changeTextDebouncer} />;
}
}https://stackoverflow.com/questions/41210867
复制相似问题