【问题标题】:Debouncing not working with React-Redux app去抖动不适用于 React-Redux 应用程序
【发布时间】:2016-12-01 14:11:38
【问题描述】:

我正在构建一个在按键上执行 API 请求的函数,但我希望它去抖动。

这目前不起作用并产生错误:lodash.js:10319 Uncaught TypeError: Expected a function

这是一个带有控制台日志而不是异步请求的代码 sn-p,它也不起作用!

import React from 'react';
const _ = require('lodash');

const method = () => {
    return _.debounce(testFunc(), 3000);
};

const testFunc = () => {
    console.log('echo echo test test');
};


const SearchBox = ({ onTypingSearch, searchTerm }) => (
    <form>
        <p>Search: {searchTerm}</p>
        <input
            onChange={(e) => {
                console.log(e.target.value);                
                onTypingSearch(e.target.value);
                console.log(method);
                method();
            }}
                value={searchTerm}
        />
  </form>
);

export default SearchBox;

【问题讨论】:

    标签: javascript reactjs redux lodash


    【解决方案1】:

    你必须去抖动函数,而不是调用它的结果:

    这个:

    const method = () => {
        return _.debounce(testFunc(), 3000);
    };
    

    到这里:

    const method = () => {
        return _.debounce(testFunc, 3000);
    };
    

    更新:

    按照您的设置方式,method 返回一个去抖函数。所以调用method() 将返回一个函数。然后你必须调用它:method()()

    最好这样做:

    const method = _.debounce(() => {
        return testFunc();
    }, 3000);
    

    如果你想要 args:

    const method = _.debounce((e) => {
        return testFunc(e);
    }, 3000);
    

    然后,您可以继续按照您当前的方式拨打电话:method()

    【讨论】:

    • 我试过了,但是我的函数没有被执行?
    • 另外,如果需要,您将如何将参数传递给函数?
    • 来自docsThe func is invoked with the last arguments provided to the debounced function
    • 非常感谢,从另一个函数声明一个函数对我来说有点陌生
    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 2021-01-03
    • 2020-06-24
    • 2018-01-12
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多