javascript - 去抖动不适用于 React-Redux 应用程序

标签 javascript reactjs redux lodash

我正在构建一个在按键时执行 API 请求的函数,但我希望它能够消除抖动。

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

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

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;

最佳答案

您必须对函数进行反跳,而不是调用它的结果:

这个:

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

对此:

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

更新:

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

最好这样做:

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

如果你想要参数:

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

然后,您可以继续按照当前的方式调用:method()

关于javascript - 去抖动不适用于 React-Redux 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40912803/

相关文章:

javascript - 回调函数作为带参数的字符串

javascript - 在 Intellij Idea 中启用对 Ext.js 的 JSHint 支持

reactjs - React-bootstrap 弹出窗口 : Not positioned where I expect it

javascript - 我为状态创建了一个通用的 reducer ,什么时候应该使用它什么时候不应该使用它

javascript - 在 react 中将 redux prop 从容器传递到演示组件时,出现 TypeError : _this2. props.handleClick 不是一个函数

reactjs - React Redux 容器组件

javascript - 云代码 - Parse.Object 初始值设定项不起作用

javascript - 使用angularjs用数组值替换数学方程式中的变量?

python - 如何结合 javascript/react 前端和 python 后端?

javascript - `|` 在 Flow 中的这个对象中做什么?