我试图在我的React应用程序中添加去抖功能,并且希望在没有诸如loadash,第三方节点模块等库的情况下进行。我尝试了一些帖子,但对我没有任何帮助。
基本上,在handleSearch中,我只是调度redux操作,该操作执行对API端点的查询,并在输入绑定(bind)值中对redux状态的pice进行调用,并调用handleSearch onChange。
我的代码是:

const handleSearch = (e: React.FormEvent<HTMLInputElement>) => {
        const value = e.currentTarget.value
        dispatch(setSearch(value))
    }
然后回头
<input type="text" value={searchQuery} onChange={handleSearch} />
另外,我的 Action :
export const searchMovies = (category: String, searchQuerry: string) => async (dispatch: Dispatch<ControlDispatchTypes>) => {
    try {
        dispatch({
            type: SEARCH_LIST_LOADING
        })
        let res: any;

        if (searchQuerry.length >= 3) {
            res = await axios.get(`https://api.themoviedb.org/3/search/${category}?api_key=xxxxxxxxxx&query=${searchQuerry}`)
        }

        dispatch({
            type: SEARCH_LIST_SUCCESS,
            payload: res.data.results
        })

    } catch (error) {
        dispatch({
            type: SEARCH_LIST_FAIL
        })
    }
}
和用于搜索的 reducer 的一部分:
...
 case SET_SEARCH:
            return {
                ...state,
                search: action.payload
            }
        case SEARCH_LIST_LOADING:
            return {
                ...state,
                searchLoading: false
            }
        case SEARCH_LIST_SUCCESS:
            return {
                ...state,
                searchLoading: false,
                items: action.payload

            }
        case SEARCH_LIST_FAIL:
            return {
                ...state,
                searchLoading: false
            }
...

最佳答案

我已经看到React Redux项目使用此资源为项目添加去抖动功能。取自https://davidwalsh.name/javascript-debounce-function

export const debounce = (func, wait, immediate) => {
    let timeout;
    return function () {
        const later = () => {
            timeout = null;
            if (!immediate) func.apply(this, arguments);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(this, arguments);
    };
};

07-24 16:41