繁体   English   中英

在 React 中再次调用 function 时,Lodash _.debounce 不会取消现有计时器

[英]Lodash _.debounce is not canceling existing timer when function is called again in React

我正在尝试为我的 React 组件中的表单消除 onChange 事件。 我计划将debounceStateUpdate移动到 static 中,使用 function 来通用化去抖时间,这就是为什么存在额外层而不是直接使用_.debounce的原因。

const ProfileGeneralEditContent = props => {
    const debounceStateUpdate = updateFunction => {
        return _.debounce(params => updateFunction(params), 700);
    };

    const FormsyFieldUpdated = debounceStateUpdate((config) => {
        console.log("update some things here");
    });

    return (
        <Formsy
            onChange={(config) => {
                FormsyFieldUpdated.cancel();
                FormsyFieldUpdated(config);
            }}
            onInvalid={() => setValid(false)}
            onValid={() => setValid(true)}
        >
            <div className={'flex justify-start items-start'}>
            .
            .
            . (more jsx)

我认为当onChange事件触发时, cancel()调用将取消任何正在运行的现有去抖动定时器并启动一个新的。

我的目标是在每次按键时消除更新 state 的输入,这样 state 只会在 700 毫秒无更新后更新。 但是目前,此代码仅将每次按键的 state 更新延迟 700 毫秒,并且每次按键的 state 更新仍在进行中。

如何使用_.debounce来保持一个运行的去抖定时器来延迟我的 state 更新,而不是为每个按下的键一次运行 10 个定时器?

我想到了。 我需要在useCallback()中包装我的去抖 function 定义,因为组件的重新渲染正在重新定义每次按键的去抖 function ,因此它不会知道其先前迭代的运行功能。

const ProfileGeneralEditContent = props => {
    const debounceStateUpdate = updateFunction => {
        return _.debounce(params => updateFunction(params), 700);
    };

    const FormsyFieldUpdated = useCallback(debounceStateUpdate((config) => {
        console.log("update some things here");
    }), []);

    return (
        <Formsy
            onChange={(config) => FormsyFieldUpdated(config)}
            onInvalid={() => setValid(false)}
            onValid={() => setValid(true)}
        >
            <div className={'flex justify-start items-start'}>
            .
            .
            . (more jsx)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM