2017-08-25 47 views
1

我有下面的反应组件。 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; 
+0

[使用jQuery $(本)与ES6箭头功能(词法这种结合)的可能的复制(https://stackoverflow.com/questions/ 27670401 /使用-jquery的此结果与-ES6箭头函数-词法此结合) – no1xsyzy

回答

3

_.debounce只是返回一个必须调用的函数。试着改变你的一样代码:

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

_.debounce表示,它

(功能):返回新的去抖功能。

,所以你需要调用它像

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

debounced();