简体   繁体   中英

How i can correctly debounce mapDispatchToProps or redux action?

I have redux action:

export const setSearchText = payload => ({
  type: SEARCH_ACTION,
  payload,
});

And following mapDispatchToPros:

const mapDispatchToProps = dispatch => ({
  onChange: (...args) => setSearchText(...args),
});

How i can it debounce?

const mapDispatchToProps = dispatch => ({
  onChange: (...args) =>{
    setTimeout(()=>dispatch(setSearchText(...args)),1000);
  }
});

Here the debounce time is set to 1 sec

Hope this code works

  onChange: (...args) => debounce(() => dispatch(setSearchText(...args)), 500)

This is the debounce function.

const debounce = (func, wait) => {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    const later = function() {
      timeout = null;
      func.apply(context, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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