Lodash用React Input去抖动

Mic*_*man 11 relay debouncing lodash reactjs

我正在尝试将lodash的debouncing添加到搜索函数中,从输入onChange事件调用.下面的代码生成一个类型错误'function is function',我理解,因为lodash期待一个函数.这样做的正确方法是什么,可以全部内联完成吗?到目前为止,我几乎尝试了所有的例子都无济于事.

search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }), 500);
},
Run Code Online (Sandbox Code Playgroud)

Jef*_*den 20

去抖函数可以在JSX中内联传递,也可以直接设置为类方法,如下所示:

search: _.debounce(function(e) {
  console.log('Debounced Event:', e);
}, 1000)
Run Code Online (Sandbox Code Playgroud)

小提琴: 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)
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢那。我现在看到的是合成事件的控制台日志,我需要 e.target.value 来执行搜索.. 我试过 e.persist() 但它似乎没有做任何事情。去抖动在技术上是有效的,但如果没有传递一个值,它就不起作用。谢谢你的帮助。 (2认同)

Axi*_*ili 20

这就是我在谷歌搜索一整天后不得不这样做的方式。

const MyComponent = (props) => {
  const [reload, setReload] = useState(false);

  useEffect(() => {
    if(reload) { /* Call API here */ }
  }, [reload]);

  const callApi = () => { setReload(true) }; // You might be able to call API directly here, I haven't tried
  const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));

  function handleChange() { 
    debouncedCallApi(); 
  }

  return (<>
    <input onChange={handleChange} />
  </>);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

使用功能性反应组件尝试使用useCallback. useCallback记住你的 debounce 函数,所以它不会在组件重新渲染时一次又一次地重新创建。没有useCallback去抖功能将不会与下一个击键同步。

`

import {useCallback} from 'react';
import _debouce 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} />
}
Run Code Online (Sandbox Code Playgroud)

`