我正在研究 React Native 和 lodash 的去抖动。
使用下面的代码只会让它像延迟一样工作,而不是去抖动。
<Input
onChangeText={(text) => {
_.debounce(()=> console.log("debouncing"), 2000)()
}
/>
如果我输入“foo”这样的输入,我希望控制台只记录一次去抖动。现在它记录了 3 次“去抖动”。
最佳答案
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} />
}
}
关于javascript - react native : Using lodash debounce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210867/