Lodash用React Input去抖动

时间:2016-03-29 20:06:24

标签: reactjs lodash relay debouncing

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

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

11 个答案:

答案 0 :(得分:17)

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)
}

答案 1 :(得分:1)

这不是那么简单的问题

一方面只是解决你遇到的错误,你需要在函数中包含s

indexOf()

另一方面,我相信去抖动逻辑必须包含在Relay中。

答案 2 :(得分:1)

这是我整天搜索一次后要做的。

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} />
  </>);
}

答案 3 :(得分:1)

我发现这里的很多答案都过于复杂或不准确(即实际上并未消除抖动)。这是一个带检查的简单解决方案:

const [count, setCount] = useState(0); // simple check debounce is working
const handleChangeWithDebounce = _.debounce(async (e) => {
    if (e.target.value && e.target.value.length > 4) {
        // TODO: make API call here
        setCount(count + 1);
        console.log('the current count:', count)
    }
}, 1000);
<input onChange={handleChangeWithDebounce}></input>

答案 4 :(得分:1)

对于功能性反应组件,请尝试使用 useCallbackuseCallback 会记住您的 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} />
}

`

答案 5 :(得分:0)

对于您的情况,应为:

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

答案 6 :(得分:0)

class MyComp extends Component {
  debounceSave;
  constructor(props) {
    super(props);
  }
  this.debounceSave = debounce(this.save.bind(this), 2000, { leading: false, trailing: true });
}

save()是要调用的函数

debounceSave()是您实际调用的函数(多次)。

答案 7 :(得分:0)

这对我有用:

handleChange(event) {
  event.persist();
  const handleChangeDebounce = _.debounce((e) => {
    if (e.target.value) {
      // do something
    } 
  }, 1000);
  handleChangeDebounce(event);
}

答案 8 :(得分:0)

这是正确的 FC 方法 @

Aximili 回答只触发一次

import { SyntheticEvent } from "react"

export type WithOnChange<T = string> = {
    onChange: (value: T) => void
}

export type WithValue<T = string> = {
    value: T
}

//  WithValue & WithOnChange
export type VandC<A = string> = WithValue<A> & WithOnChange<A>

export const inputValue = (e: SyntheticEvent<HTMLElement & { value: string }>): string => (e.target as HTMLElement & { value: string }).value

const MyComponent: FC<VandC<string>> = ({ onChange, value }) => {
    const [reload, setReload] = useState(false)
    const [state, setstate] = useState(value)
    useEffect(() => {
        if (reload) {
            console.log('called api ')
            onChange(state)
            setReload(false)
        }
    }, [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(x:string) {
        setstate(x)
        debouncedCallApi()
    }

    return (<>
        <input
            value={state} onChange={_.flow(inputValue, handleChange)} />
    </>)
}


答案 9 :(得分:-1)

@Aximili

const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));

看起来很奇怪:)我用useCallback宣传解决方案:

const [searchFor, setSearchFor] = useState('');

const changeSearchFor = debounce(setSearchFor, 1000);
const handleChange = useCallback(changeSearchFor, []);

答案 10 :(得分:-2)

    const delayedHandleChange = debounce(eventData => someApiFunction(eventData), 500);

const handleChange = (e) => {
        let eventData = { id: e.id, target: e.target };
        delayedHandleChange(eventData);
    }