【问题标题】:debounced function not being called in a react component没有在反应组件中调用去抖动函数
【发布时间】:2017-08-25 03:41:20
【问题描述】:

我有下面的反应组件。 调用 raiseCriteriaChange 方法,但从未到达 this.props.onCriteriaChange(this.state.criteria) 行。

任何想法为什么代码永远不会到达 this.props.onCriteriaChange

import * as React from 'react';
import { debounce } from 'lodash';

interface CustomerSearchCriteriaProps {
  onCriteriaChange: (criteria: string) => void;
}
interface CustomerSearchCriteriaState {
  criteria: string;
}

class CustomerSearchCriteria extends React.Component<CustomerSearchCriteriaProps, CustomerSearchCriteriaState> {

  constructor() {
    super();

    this.state = {
      criteria: ''
    };
  }

  // problem method:
  raiseCriteriaChange = () => {
    // the call reaches here fine ...
    debounce(
    () => {
       // ... but the call never reaches here ... why is this?
       this.props.onCriteriaChange(this.state.criteria);
    },  
    300);
  }

  handleCriteriaChange = (e: React.FormEvent<HTMLInputElement>) => {
    this.setState({ criteria: e.currentTarget.value }, () => {
      this.raiseCriteriaChange();
    });
  }

  render() {

    return (
      <div className="input-group">
        <input
          type="text" 
          value={this.state.criteria} 
          onChange={this.handleCriteriaChange} 
          className="form-control"
        />
      </div>
    );
  }
}

export default CustomerSearchCriteria;

【问题讨论】:

标签: javascript reactjs typescript lodash es6-class


【解决方案1】:

_.debounce 只返回一个必须调用的函数。尝试更改您的代码,例如:

raiseCriteriaChange = debounce(() => {
    this.props.onCriteriaChange(this.state.criteria);
}, 300);

【讨论】:

    【解决方案2】:

    _.debounce,上面写着

    (Function):返回新的去抖函数。

    所以你需要像这样称呼它

    var debounced = debounce(
        () => {
           // ... but the call never reaches here ... why is this?
           this.props.onCriteriaChange(this.state.criteria);
        },  
        300
    );
    
    debounced();
    

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2017-06-12
      • 2020-03-27
      相关资源
      最近更新 更多