简体   繁体   English

redux thunk内部的反跳方法

[英]debounce method inside redux thunk

I have action with async method inside and I want to debounce it 我在内部使用异步方法进行操作,我想对其进行反跳

export const onSearchChange = query => dispach => {
    if (query === "") {
        dispach({ type: SOME_TYPE, payload: query })
    } else {
        dispach({ type: SOME_TYPE, payload: query })
        searchProductsCall(query).then(payload => {
            dispach({ type: SOME_OTHER_TYPE, payload })
        })
    }
}

how can I debounce searchProductsCall using lodash or something else ? 我该怎么抖searchProductsCall使用lodash或其他什么东西?

You need to create the debounced function first and call that function instead of your searchProductsCall . 您需要先创建去抖动的函数,然后调用该函数,而不是searchProductsCall

The following code should make sure the first dispatch is called right away in all cases (it probably changes the UI?) and that it calls the searchProductsCall only after the debounce and when there is a non-empty query. 以下代码应确保在所有情况下都立即调用第一次调度(它可能会更改UI?),并且只有在反跳之后以及有非空查询时才调用searchProductsCall

export const debouncedSearchProductsCall = _.debounce((query, dispatch) => {
    if (query !== "") {
        searchProductsCall(query).then(payload => {
            dispatch({ type: SOME_OTHER_TYPE, payload })
        });
    }
}, 200);

export const onSearchChange = query => dispatch => {
    dispatch({ type: SOME_TYPE, payload: query });
    debouncedSearchProductsCall(query, dispatch);
}

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

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