Lodash的反跳在React中不起作用 [英] Lodash debounce not working in React

查看:49
本文介绍了Lodash的反跳在React中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好先看一下我的代码:

it would be best to first look at my code:

import React, { Component } from 'react';
import _ from 'lodash';
import Services from 'Services'; // Webservice calls

export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value || null
    }
  }

  onChange(value) {
    this.setState({ value });

    // This doesn't call Services.setValue at all
    _.debounce(() => Services.setValue(value), 1000);
  }

  render() {
    return (
      <div>
        <input 
          onChange={(event, value) => this.onChange(value)}
          value={this.state.value}
        />
      </div>
    )
  }
}

只需一个简单的输入.在构造器它抓住<代码>值从道具(如果有的话)在套的局部状态的部件.

Just a simple input. In the contructor it grabs value from the props (if available) at sets a local state for the component.

然后在 input onChange 函数中,我更新状态,然后尝试调用Webservice端点以使用 Services.setValue().

Then in the onChange function of the input I update the state and then try to call the webservice endpoint to set the new value with Services.setValue().

起作用的是,如果我直接通过输入的 onChange 设置去抖,如下所示:

What does work is if I set the debounce directly by the onChange of the input like so:

<input 
  value={this.state.value} 
  onChange={_.debounce((event, value) => this.onChange(value), 1000)} 
/>

但是随后 this.setState 仅每1000毫秒被调用一次并更新视图.因此,在文本字段中键入内容最终看起来很奇怪,因为您键入的内容只会在稍后显示.

But then this.setState gets called only every 1000 milliseconds and update the view. So typing in a textfield ends up looking weird since what you typed only shows a second later.

在这种情况下我该怎么办?

What do I do in a situation like this?

推荐答案

发生此问题是因为您没有调用反跳功能,您可以按以下方式进行操作

The problem occurs because you aren't calling the debounce function, you could do in the following manner

export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value || null
    }
    this.servicesValue = _.debounce(this.servicesValue, 1000);
  }

  onChange(value) {
    this.setState({ value });
    this.servicesValue(value);
  }
  servicesValue = (value) => {
      Services.setValue(value)
  }
  render() {
    return (
      <div>
        <input 
          onChange={(event, value) => this.onChange(value)}
          value={this.state.value}
        />
      </div>
    )
  }
}

这篇关于Lodash的反跳在React中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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