Saya memiliki komponen reaksi di bawah ini. Metode raiseCriteriaChange dipanggil tetapi baris this.props.onCriteriaChange(this.state.criteria) tidak pernah tercapai.

Adakah ide mengapa kode tidak pernah mencapai 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;
3
Carl Rippon 25 Agustus 2017, 06:41

2 jawaban

Jawaban Terbaik

_.debounce hanya mengembalikan fungsi yang harus dipanggil. Coba ubah kode Anda seperti:

raiseCriteriaChange = debounce(() => {
    this.props.onCriteriaChange(this.state.criteria);
}, 300);
4
Saravana 25 Agustus 2017, 03:48

Lihat _.debounce, yang mengatakannya

(Fungsi): Mengembalikan fungsi baru yang di-debounce.

Jadi Anda perlu menyebutnya seperti

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

debounced();
2
leaf 25 Agustus 2017, 03:49