39

入力 onChange イベントから呼び出される検索機能に、lodash によるデバウンスを追加しようとしています。以下のコードは、「関数が期待されています」という型エラーを生成します。これは、lodash が関数を期待しているためです。これを行う正しい方法は何ですか?すべてインラインで実行できますか? これまでSOでほぼすべての例を試しましたが、役に立ちませんでした。

search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }), 500);
},
4

12 に答える 12

37

デバウンス関数は、JSX でインラインで渡すか、次のようにクラス メソッドとして直接設定できます。

search: _.debounce(function(e) {
  console.log('Debounced Event:', e);
}, 1000)

フィドル: https://jsfiddle.net/woodenconsulting/69z2wepo/36453/

es2015+ を使用している場合は、デバウンス メソッドを直接、constructorまたは のようなライフサイクル メソッドで定義できますcomponentWillMount

例:

class DebounceSamples extends React.Component {
  constructor(props) {
    super(props);

    // Method defined in constructor, alternatively could be in another lifecycle method
    // like componentWillMount
    this.search = _.debounce(e => {
      console.log('Debounced Event:', e);
    }, 1000);
  }

  // Define the method directly in your class
  search = _.debounce((e) => {
    console.log('Debounced Event:', e);
  }, 1000)
}
于 2016-03-29T21:43:32.863 に答える
22

機能的な反応コンポーネントでは、 を使用してみてくださいuseCallbackuseCallbackコンポーネントが再レンダリングされるときに何度も再作成されないように、デバウンス関数をメモします。デバウンス機能がないuseCallbackと、次のキーストロークと同期しません。

`

import {useCallback} from 'react';
import _debounce from 'lodash/debounce';
import axios from 'axios';

function Input() {
    const [value, setValue] = useState('');

    const debounceFn = useCallback(_debounce(handleDebounceFn, 1000), []);

    function handleDebounceFn(inputValue) {
        axios.post('/endpoint', {
          value: inputValue,
        }).then((res) => {
          console.log(res.data);
        });
    }


    function handleChange (event) {
        setValue(event.target.value);
        debounceFn(event.target.value);
    };

    return <input value={value} onChange={handleChange} />
}

`

于 2021-06-11T17:29:32.843 に答える
3

そんなに簡単な質問じゃない

一方では、取得しているエラーを回避するsetVariablesには、関数でラップする必要があります。

 search(e){
  let str = e.target.value;
  _.debounce(() => this.props.relay.setVariables({ query: str }), 500);
}

一方、デバウンス ロジックは Relay 内にカプセル化する必要があると私は信じています。

于 2016-03-29T20:14:01.730 に答える
0

これは私のために働いた:

handleChange(event) {
  event.persist();
  const handleChangeDebounce = _.debounce((e) => {
    if (e.target.value) {
      // do something
    } 
  }, 1000);
  handleChangeDebounce(event);
}
于 2021-01-12T09:57:42.630 に答える