Lodash 使用 React 输入去抖动

新手上路,请多包涵

我正在尝试将使用 lodash 的去抖动添加到从输入 onChange 事件调用的搜索函数中。下面的代码生成一个类型错误’函数是预期的’,我理解这是因为 lodash 需要一个函数。这样做的正确方法是什么,可以全部内联吗?到目前为止,我已经尝试了几乎所有关于 SO 的示例,但均无济于事。

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

原文由 Michael Kaufman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 790
2 个回答

debounce 函数可以在 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)
}

原文由 Jeff Wooden 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用功能性反应组件尝试使用 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} />
}

`

原文由 Jules Patry 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进