功能组件中的去抖动

问题描述

我有这个带去抖动功能的组件:

import React,{useCallback,Component,useState} from 'react';
import debounce from 'lodash.debounce';

function Tags() {

const [type,setType] = useState('');
...

    async function getSearchTag(keyword) {
       ....
       await axios.post(ajax_url,{keyword,tags : disabled_tags});

    };


    const onChangeDebounced = useCallback(debounce(getSearchTag(value),500),[value]);
    

    const handleInputChange = (event) => {

        // Immediately update the state
        setValue(event.target.value);

        // Execute the debounced onChange method
        onChangeDebounced(event.target.value);
    }

    return (
        <div>
        ...
        <input type="text" name="tags" placeholder="Search for other tags..." onChange={(e) => 
        handleInputChange(e)}/>
        </div>
    );
}

export default Tags;

这是我第一次在 React 中设置 debounce,我正在尝试将现有的 react class component 转换为 react functional component

我需要将 value state 传递给 getSearchTag(),以上实现是否正确?

解决方法

您已将依赖项作为值添加到 useCallback,这会导致新的每次值状态更改时都会创建去抖动函数,这是导致问题的原因。

另外你只需要pass a function reference to debounce而不是调用它

您创建去抖动函数的更新方式如下

const onChangeDebounced = useCallback(debounce(getSearchTag,500),[]);