[英]Debouncing not working with React-Redux app
I'm building a function that performs an API request on keypress, but I want this debounced. 我正在构建一个在按键上执行API请求的函数,但是我希望将其反跳。
This doesn't currently work and produces an error: lodash.js:10319 Uncaught TypeError: Expected a function
当前这不起作用,并产生错误: lodash.js:10319 Uncaught TypeError: Expected a function
Here's a code snippet with a console log instead of async request, which also doesn't work! 这是一个带有控制台日志而不是异步请求的代码片段,这也不起作用!
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;
You have to debounce the function, not the result of calling it: 您必须对函数进行去抖动,而不是调用它的结果:
This: 这个:
const method = () => {
return _.debounce(testFunc(), 3000);
};
To this: 对此:
const method = () => {
return _.debounce(testFunc, 3000);
};
Update: 更新:
The way you have set this up, method
returns a debounced function. 您设置method
将返回一个反跳功能。 So calling method()
will return a function. 因此,调用method()
将返回一个函数。 Then you will have to call it: method()()
. 然后,您必须调用它: method()()
。
It is better to do this: 最好这样做:
const method = _.debounce(() => {
return testFunc();
}, 3000);
And if you want args: 如果您想要args:
const method = _.debounce((e) => {
return testFunc(e);
}, 3000);
Then, you can continue calling the way you are doing at the moment: method()
. 然后,您可以继续调用当前操作方式: method()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.