[英]Why my debounce function returns undefined value?
well it's seem delayHandler
is no a function that take the value as params and send it to debounce
you should do like this and it will work:好吧,似乎
delayHandler
不是 function 将值作为参数并将其发送到debounce
,您应该这样做,它会起作用:
import React, { useState } from "react";
import "./styles.css";
function debounce(fn, ms, ...args) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, ms);
};
}
export default function App() {
const [value, setValue] = useState("");
const handleChange = e => {
const { value } = e.target;
delayHandler(value)();
};
const delayHandler = v =>
debounce(
value => {
setValue(value);
},
2000,
v
);
return (
<div className="App">
<p>Current value: {value}</p>
<form>
<input value={value} onChange={handleChange} />
</form>
</div>
);
}
so by passing v as argument to debounce
it will apply it to fn
function.因此,通过将 v 作为参数传递给
debounce
,它将应用于fn
function。
The root of the issue is that the function returned by debounce
does not take any parameters and so when you pass in value
to delayHandler
it doesn't do anything.问题的根源在于 debounce 返回的
debounce
不带任何参数,因此当您将value
传递给delayHandler
时,它什么也不做。
Here is a working example:这是一个工作示例:
const { useState } = React; function debounce(fn, ms) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, ms); }; } function App() { const [value, setValue] = useState(""); const handleChange = e => { const { value } = e.target; delayHandler(value); }; const delayHandler = debounce(setValue, 2000); return ( <div className="App"> <p>Current value: {value}</p> <form> <input onChange={handleChange} /> </form> </div> ); } //////////////////////////////////////// const rootElement = document.getElementById("root"); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, rootElement );
<:DOCTYPE html> <html lang="en"> <head> <title>React App</title> <script src="https.//cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> </head> <body> <div id="root"></div> </body> </html>
function debounce(fn, ms, ...args) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, ms);
};
}
const delayHandler = value =>
debounce(
value => {
setValue(value);
},
2000,
value
)();
Here is the fix, when you call the debounce function you have to pass value as a parameter, otherwise the args will not contain the val.这是修复,当您调用去抖动 function 时,您必须将值作为参数传递,否则 args 将不包含 val。 By the way you don't have to implement this by yourself, you can use lodash debounce https://lodash.com/docs/4.17.15#debounce
顺便说一句,您不必自己实现,您可以使用 lodash debounce https://lodash.com/docs/4.17.15#debounce
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.