当像这样调用 debounce 函数时:
const handler = debounce(someFunction, 2000);
Run Code Online (Sandbox Code Playgroud)
它会someFunction在每次击键时调用。但是当我们将它包装在 useCallback 中时,它工作正常。
const handler = useCallback(debounce(someFunction, 2000), []);
Run Code Online (Sandbox Code Playgroud)
但据我所知, debounce 函数应该someFunction在 2000 ms 之后调用,因此不应在每次击键时调用该函数。但这不是我所期望的。
谁能解释为什么在使用 debounce 时需要 useCallback?
我正在浏览文档并发现了这段代码:
const LIMIT = 3;
const asyncIterable = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
const done = i === LIMIT;
const value = done ? undefined : i++;
return Promise.resolve({ value, done });
},
return() {
// This will be reached if the consumer called 'break' or 'return' early in the loop.
return { done: true };
},
};
},
};
(async () => {
for await (const num of asyncIterable) {
console.log(num); …Run Code Online (Sandbox Code Playgroud)