简体   繁体   English

消除 redux 调度未按预期工作

[英]debouncing a redux dispatch not working as expected

Im trying to debounce a api action which is a dispatch call to reducer.The api call in the browser should debounce after a particular delay given as a single api , but its going as multiple api calls after the delay ,the code is as follows.我试图去抖动一个 api 动作,它是对 reducer 的调度调用。浏览器中的 api 调用应该在作为单个 api 给出的特定延迟后去抖动,但在延迟后它会作为多个 api 调用,代码如下。

please refer the screenshot also请参考屏幕截图在此处输入图片说明

const apiCall = (args) => {
        dispatch(getECByStatus({status: 'PENDING_APPROVAL', search: args}))
    }

    const debounce = (apiFunc, delay) => {
        let inDebounce
        return function () {
            const context = this
            const args = arguments
            clearTimeout(inDebounce)
            inDebounce = setTimeout(() => {
                inDebounce = null
                apiFunc.apply(context, args)
            },delay);
        }
    }

    const optimizedVersion = debounce(apiCall, 600)

const handleSearchChange = (value) => {

        optimizedVersion(value)
    }

the handleSearchChange is the onchange event fired from the input box on typing the input. handleSearchChange是在输入输入时从输入框触发的 onchange 事件。 getECByStatus is a redux action creator, which calls api with the search param, getECByStatus是一个 redux 动作创建者,它使用搜索参数调用 api,

export const getECByStatus = (params) => async (dispatch) => {
    let editCheckType = params?.type ? `/${params.type}` : ''
    let searchParams = params?.search ? `&search=${params.search}` : ''

    try {
        dispatch({
            type: actionType.GET_EC_BY_STATUS_REQUEST,
            payload: {
                load: true,
            },
        })
        let study_id = getItem('study_id')
        const { data } = await DataService.get(
            `/edit-checks${editCheckType}?status=${params.status}&study_id=${study_id}${searchParams}`
        )

        dispatch({
            type: actionType.GET_EC_BY_STATUS_SUCCESS,
            payload: {
                load: false,
                data: data.data,
                }
            },
        })
    } catch (error) {
        console.error('Get EC by status error', error)
        dispatch({
            type: actionType.GET_EC_BY_STATUS_FAIL,
            payload: {
                load: false,
            },
        })
    }
}

Thanks in advance!提前致谢!

这是因为在 dispatch 事件被触发后 UI 重新渲染,因为输入框是一个受控的,我们必须将更新的值传递给输入框组件,所以我们可以传递一个 ref 来不重新渲染用户界面。

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

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