React Native:使用lodash debounce [英] React Native: Using lodash debounce

查看:528
本文介绍了React Native:使用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之类的输入,我希望控制台只记录一次debounce。现在它记录debounce3次。

I want the console to log debounce only once if I enter an input like "foo". Right now it logs "debounce" 3 times.

推荐答案

去抖函数应该在render方法之外的某处定义,因为它必须引用在每次调用它时,对函数的同一个实例反对创建一个新实例,就像现在将它放在 onChangeText 处理函数中一样。

Debounce function should be defined somewhere outside of render method since it has to refer to the same instance of the function every time you call it as oppose to creating a new instance like it's happening now when you put it in the onChangeText handler function.

定义去抖功能的最常见位置是在组件的对象上。这是一个例子:

The most common place to define a debounce function is right on the component's object. Here's an example:

class MyComponent extends React.Component {
  constructor() {
    this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000);
  }

  onChangeText(text) {
    console.log("debouncing");
  }

  render() {
    return <Input onChangeText={this.onChangeTextDelayed} />
  }
}

这篇关于React Native:使用lodash debounce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆