我正在尝试在函数组件中使用lodash中的{'id': 613, 'name': "new year's eve"}
方法,例如:
throttle
由于在每次渲染时都重新声明了const App = () => {
const [value, setValue] = useState(0)
useEffect(throttle(() => console.log(value), 1000), [value])
return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}
中的方法,因此节流效果不起作用。
有人有一个简单的解决方案吗?
答案 0 :(得分:18)
我创建了一个名为useDebouncedEffect
的自定义钩子,它将等待执行useEffect
,直到在延迟时间内状态没有更新。
在此示例中,您的效果将在您停止单击按钮1秒钟后登录到控制台。
App.jsx
import { useState } from "react";
import { useDebouncedEffect } from "./useDebouncedEffect";
const App = () => {
const [value, setValue] = useState(0)
useDebouncedEffect(() => console.log(value), 1000, [value])
return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}
useDebouncedEffect.js
import { useCallback, useEffect } from "react";
export const useDebouncedEffect = (effect, delay , deps) => {
const callback = useCallback(effect, deps);
useEffect(() => {
const handler = setTimeout(() => {
callback();
}, delay);
return () => {
clearTimeout(handler);
};
}, [callback, delay]);
}
答案 1 :(得分:8)
useThrottle
,useDebounce
const App = () => {
const [value, setValue] = useState(0);
// called at most once per second (same API with useDebounce)
const throttledCb = useThrottle(() => console.log(value), 1000);
// usage with useEffect: invoke throttledCb on value change
useEffect(throttledCb, [value]);
// usage as event handler
<button onClick={throttledCb}>log value</button>
// ... other render code
};
useThrottle
(Lodash)import _ from "lodash"
function useThrottle(cb, delay) {
const options = { leading: true, trailing: false }; // add custom lodash options
const cbRef = useRef(cb);
// use mutable ref to make useCallback/throttle not depend on `cb` dep
useEffect(() => { cbRef.current = cb; });
return useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
}
const App = () => {
const [value, setValue] = useState(0);
const invokeDebounced = useThrottle(
() => console.log("changed throttled value:", value),
1000
);
useEffect(invokeDebounced, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p>value will be logged at most once per second.</p>
</div>
);
};
function useThrottle(cb, delay) {
const options = { leading: true, trailing: false }; // pass custom lodash options
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
useDebounce
(Lodash)import _ from "lodash"
function useDebounce(cb, delay) {
// ...
const inputsRef = useRef(cb); // mutable ref like with useThrottle
useEffect(() => { inputsRef.current = { cb, delay }; }); //also track cur. delay
return useCallback(
_.debounce((...args) => {
// Debounce is an async callback. Cancel it, if in the meanwhile
// (1) component has been unmounted (see isMounted in snippet)
// (2) delay has changed
if (inputsRef.current.delay === delay && isMounted())
inputsRef.current.cb(...args);
}, delay, options
),
[delay, _.debounce]
);
}
const App = () => {
const [value, setValue] = useState(0);
const invokeDebounced = useDebounce(
() => console.log("debounced", value),
1000
);
useEffect(invokeDebounced, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p> Logging is delayed until after 1 sec. has elapsed since the last invocation.</p>
</div>
);
};
function useDebounce(cb, delay) {
const options = {
leading: false,
trailing: true
};
const inputsRef = useRef(cb);
const isMounted = useIsMounted();
useEffect(() => {
inputsRef.current = { cb, delay };
});
return useCallback(
_.debounce(
(...args) => {
// Don't execute callback, if (1) component in the meanwhile
// has been unmounted or (2) delay has changed
if (inputsRef.current.delay === delay && isMounted())
inputsRef.current.cb(...args);
},
delay,
options
),
[delay, _.debounce]
);
}
function useIsMounted() {
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
return () => isMountedRef.current;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
1。您可以用自己的throttle
或debounce
代码替换Lodash,例如:
const debounceImpl = (cb, delay) => {
let isDebounced = null;
return (...args) => {
clearTimeout(isDebounced);
isDebounced = setTimeout(() => cb(...args), delay);
};
};
const throttleImpl = (cb, delay) => {
let isThrottled = false;
return (...args) => {
if (isThrottled) return;
isThrottled = true;
cb(...args);
setTimeout(() => {
isThrottled = false;
}, delay);
};
};
const App = () => {
const [value, setValue] = useState(0);
const invokeThrottled = useThrottle(
() => console.log("throttled", value),
1000
);
const invokeDebounced = useDebounce(
() => console.log("debounced", value),
1000
);
useEffect(invokeThrottled, [value]);
useEffect(invokeDebounced, [value]);
return <button onClick={() => setValue(value + 1)}>{value}</button>;
};
function useThrottle(cb, delay) {
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
throttleImpl((...args) => cbRef.current(...args), delay),
[delay]
);
}
function useDebounce(cb, delay) {
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
debounceImpl((...args) => cbRef.current(...args), delay),
[delay]
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
2。如果始终与useThrottle
(与useEffect
相同)使用,则useDebounce
可以缩短:
const App = () => {
// useEffect now is contained inside useThrottle
useThrottle(() => console.log(value), 1000, [value]);
// ...
};
const App = () => {
const [value, setValue] = useState(0);
useThrottle(() => console.log(value), 1000, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p>value will be logged at most once per second.</p>
</div>
);
};
function useThrottle(cb, delay, additionalDeps) {
const options = { leading: true, trailing: false }; // pass custom lodash options
const cbRef = useRef(cb);
const throttledCb = useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
useEffect(() => {
cbRef.current = cb;
});
// set additionalDeps to execute effect, when other values change (not only on delay change)
useEffect(throttledCb, [throttledCb, ...additionalDeps]);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
答案 2 :(得分:8)
您可能(可能需要)WEBSITE_MAX_DYNAMIC_APPLICATION_SCALE_OUT
在渲染之间存储值。就像useRef
类似的东西
const App = () => {
const [value, setValue] = useState(0)
const throttled = useRef(throttle((newValue) => console.log(newValue), 1000))
useEffect(() => throttled.current(value), [value])
return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}
关于useCallback
:
它可能也可以工作
const throttled = useCallback(throttle(newValue => console.log(newValue), 1000), []);
但是,如果我们尝试在更改value
后重新创建回调,则:
const throttled = useCallback(throttle(() => console.log(value), 1000), [value]);
我们可能会发现它不会延迟执行:value
更改后,会立即重新创建并执行回调。
因此,我看到useCallback
在延迟运行的情况下无法提供明显的优势。由你决定。
[UPD]最初是
const throttled = useRef(throttle(() => console.log(value), 1000))
useEffect(throttled.current, [value])
,但是通过封闭,throttled.current
已绑定到初始value
(共0个)。因此,即使在下一个渲染中也从未改变过。
由于闭包功能,在将函数推入useRef
时要小心。
答案 3 :(得分:2)
在尝试解决陈旧状态问题时,我刚刚想到了以下模式:
我们可以将去抖动的函数存储在 ref 中,并在每次组件在 useEffect 中重新渲染时更新它,如下所示:
// some state
const [counter, setCounter] = useState(0);
// store a ref to the function we will debounce
const increment = useRef(null);
// update the ref every time the component rerenders
useEffect(() => {
increment.current = () => {
setCounter(counter + 1);
};
});
// debounce callback, which we can call (i.e. in button.onClick)
const debouncedIncrement = useCallback(
debounce(() => {
if (increment) {
increment.current();
}
}, 1500),
[]
);
// cancel active debounces on component unmount
useEffect(() => {
return () => {
debouncedIncrement.cancel();
};
}, []);
代码沙箱:https://codesandbox.io/s/debounced-function-ref-pdrfu?file=/src/index.js
我希望这可以为某人节省几个小时的努力
答案 4 :(得分:2)
还有一个实现。自定义钩子:
function useThrottle (func, delay) {
const [timeout, saveTimeout] = useState(null);
const throttledFunc = function () {
if (timeout) {
clearTimeout(timeout);
}
const newTimeout = setTimeout(() => {
func(...arguments);
if (newTimeout === timeout) {
saveTimeout(null);
}
}, delay);
saveTimeout(newTimeout);
}
return throttledFunc;
}
和用法:
const throttledFunc = useThrottle(someFunc, 200);
希望对某人有所帮助。
答案 5 :(得分:2)
在这里使用lodash的去抖功能是
import debounce from 'lodash/debounce'
// The function that we want to debounce, for example the function that makes the API calls
const getUsers = (event) => {
// ...
}
// The magic!
const debouncedGetUsers = useCallback(debounce(getUsers, 500), [])
在您的JSX中:
<input value={value} onChange={debouncedGetUsers} />
答案 6 :(得分:2)
这是我的useDebounce
:
export function useDebounce(callback, timeout, deps) {
const timeoutId = useRef();
useEffect(() => {
clearTimeout(timeoutId.current);
timeoutId.current = setTimeout(callback, timeout);
return () => clearTimeout(timeoutId.current);
}, deps);
}
您可以像这样使用它:
const TIMEOUT = 500; // wait 500 milliseconds;
export function AppContainer(props) {
const { dataId } = props;
const [data, setData] = useState(null);
//
useDebounce(
async () => {
data = await loadDataFromAPI(dataId);
setData(data);
},
TIMEOUT,
[dataId]
);
//
}
答案 7 :(得分:2)
我想使用useState
通过节流和去抖的输入加入聚会:
// import { React, useState } from 'react' // nomral import
const { useState } = React // inline import
// Throttle
const ThrottledInput = ({ onChange, delay = 500 }) => {
const [t, setT] = useState();
const handleChange = ({ target }) => {
if (!t) setT(setTimeout(() => {
onChange(target.value)
clearTimeout(t)
setT(null)
}, delay))
}
return (
<input
placeholder="throttle"
onChange={handleChange}
/>
)
}
// Debounce
const DebouncedInput = ({ onChange, delay = 500 }) => {
const [t, setT] = useState();
const handleChange = ({ target }) => {
clearTimeout(t)
setT(setTimeout(() =>
onChange(target.value), delay))
}
return (
<input
placeholder="debounce"
onChange={handleChange}
/>
)
}
// ----
ReactDOM.render(<div>
<ThrottledInput onChange={console.log} />
<DebouncedInput onChange={console.log} />
</div>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 8 :(得分:1)
我相信这个钩子可以通过提供立即触发的选项正常工作。
import { useState, useRef, useEffect } from 'react';
const useDebounce = <T>(
value: T,
timeout: number,
immediate: boolean = true
): T => {
const [state, setState] = useState<T>(value);
const handler = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => {
if (handler.current) {
clearTimeout(handler.current);
handler.current = undefined;
} else if (immediate) {
setState(value);
}
handler.current = setTimeout(() => {
setState(value);
handler.current = undefined;
}, timeout);
}, [value, timeout, immediate]);
return state;
};
export default useDebounce;
答案 9 :(得分:1)
我做了一个简单的钩子来创建节流实例。
它采用了稍微不同的方法,每次都传入要调用的函数,而不是尝试包装它并管理突变。许多其他解决方案没有考虑到调用可能发生变化的函数。模式适用于节流或去抖动。
// useThrottle.js
import React, { useCallback } from 'react';
import throttle from 'lodash/throttle';
export function useThrottle(timeout = 300, opts = {}) {
return useCallback(throttle((fn, ...args) => {
fn(...args);
}, timeout, opts), [timeout]);
}
示例用法:
...
const throttleX = useThrottle(100);
const updateX = useCallback((event) => {
// do something!
}, [someMutableValue])
return (
<div onPointerMove={(event) => throttleX(updateX, event)}></div>
)
...
答案 10 :(得分:1)
在useCallback挂钩的帮助下进行反跳。
import React, { useState, useCallback } from 'react';
import debounce from 'lodash.debounce';
function App() {
const [value, setValue] = useState('');
const [dbValue, saveToDb] = useState(''); // would be an API call normally
// highlight-starts
const debouncedSave = useCallback(
debounce(nextValue => saveToDb(nextValue), 1000),
[], // will be created only once initially
);
// highlight-ends
const handleChange = event => {
const { value: nextValue } = event.target;
setValue(nextValue);
// Even though handleChange is created on each render and executed
// it references the same debouncedSave that was created initially
debouncedSave(nextValue);
};
return <div></div>;
}
答案 11 :(得分:0)
我编写了一个简单的useDebounce
钩子,就像useEffect
一样,它也考虑了清理工作。
import { useState, useEffect, useRef, useCallback } from "react";
export function useDebounceState<T>(initValue: T, delay: number) {
const [value, setValue] = useState<T>(initValue);
const timerRef = useRef(null);
// reset timer when delay changes
useEffect(
function () {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
},
[delay]
);
const debounceSetValue = useCallback(
function (val) {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
timerRef.current = setTimeout(function () {
setValue(val);
}, delay);
},
[delay]
);
return [value, debounceSetValue];
}
interface DebounceOptions {
imediate?: boolean;
initArgs?: any[];
}
const INIT_VALUE = -1;
export function useDebounce(fn, delay: number, options: DebounceOptions = {}) {
const [num, setNum] = useDebounceState(INIT_VALUE, delay);
// save actual arguments when fn called
const callArgRef = useRef(options.initArgs || []);
// save real callback function
const fnRef = useRef(fn);
// wrapped function
const trigger = useCallback(function () {
callArgRef.current = [].slice.call(arguments);
setNum((prev) => {
return prev + 1;
});
}, []);
// update real callback
useEffect(function () {
fnRef.current = fn;
});
useEffect(
function () {
if (num === INIT_VALUE && !options.imediate) {
// prevent init call
return;
}
return fnRef.current.apply(null, callArgRef.current);
},
[num, options.imediate]
);
return trigger;
}
要点在这里:https://gist.github.com/sophister/9cc74bb7f0509bdd6e763edbbd21ba64
这是现场演示:https://codesandbox.io/s/react-hook-debounce-demo-mgr89?file=/src/App.js
用法:
const debounceChange = useDebounce(function (e) {
console.log("debounced text change: " + e.target.value);
}, 500);
// can't use debounceChange directly, since react using event pooling
function deboucnedCallback(e) {
e.persist();
debounceChange(e);
}
// later the jsx
<input onChange={deboucnedCallback} />
答案 12 :(得分:0)
您可以使用 useMemo
钩子来优化您的节流事件处理程序
以下示例代码:
const App = () => {
const [value, setValue] = useState(0);
// ORIGINAL EVENT HANDLER
function eventHandler(event) {
setValue(value + 1);
}
// THROTTLED EVENT HANDLER
const throttledEventHandler = useMemo(() => throttle(eventHandler, 1000), [value]);
return (
<button onClick={throttledEventHandler}>Throttled Button with value: {value}</button>
)
}
答案 13 :(得分:0)
react-table
在 https://react-table.tanstack.com/docs/faq#how-can-i-debounce-rapid-table-state-changes
useAsyncDebounce
函数
答案 14 :(得分:0)
const useDebounce = (func: any) => {
const debounceFunc = useRef(null);
useEffect(() => {
if (func) {
// @ts-ignore
debounceFunc.current = debounce(func, 1000);
}
}, []);
const debFunc = () => {
if (debounceFunc.current) {
return debounceFunc.current;
}
return func;
};
return debFunc();
};
答案 15 :(得分:0)
这里有一个简单的钩子可以让您的电话去抖动。
要使用下面的代码,只需声明为这样
logf * 100
然后,这样称呼
const { debounceRequest } = useDebounce(someFn);
实施如下所示
debounceRequest();
答案 16 :(得分:0)
这是一个实际的油门钩。您可以在屏幕或组件中使用要调节的所有功能,它们将共享相同的调节。或者,您可以多次调用query = "insert into table
(imageData) values
(CONVERT(varbinary(max), '"
+ str(hex_b) + "'))"
并为各个功能使用不同的油门。
像这样使用:
useThrottle()
钩子本身:
import useThrottle from '../hooks/useThrottle';
const [navigateToSignIn, navigateToCreateAccount] = useThrottle([
() => { navigation.navigate(NavigationRouteNames.SignIn) },
() => { navigation.navigate(NavigationRouteNames.CreateAccount) }
])
答案 17 :(得分:0)
我对此很迟,但是这是一种消除setState()
/**
* Like React.setState, but debounces the setter.
*
* @param {*} initialValue - The initial value for setState().
* @param {int} delay - The debounce delay, in milliseconds.
*/
export const useDebouncedState = (initialValue, delay) => {
const [val, setVal] = React.useState(initialValue);
const timeout = React.useRef();
const debouncedSetVal = newVal => {
timeout.current && clearTimeout(timeout.current);
timeout.current = setTimeout(() => setVal(newVal), delay);
};
React.useEffect(() => () => clearTimeout(timeout.current), []);
return [val, debouncedSetVal];
};
答案 18 :(得分:0)
就我而言,我还需要通过活动。与此:
const MyComponent = () => {
const handleScroll = useMemo(() => {
const throttled = throttle(e => console.log(e.target.scrollLeft), 300);
return e => {
e.persist();
return throttled(e);
};
}, []);
return <div onScroll={handleScroll}>Content</div>;
};
答案 19 :(得分:0)
可能是一个很小的自定义钩子,如下所示:
useDebounce.js
import React, { useState, useEffect } from 'react';
export default (value, timeout) => {
const [state, setState] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setState(value), timeout);
return () => clearTimeout(handler);
}, [value]);
return state;
}
用法示例:
import React, { useEffect } from 'react';
import useDebounce from '/path/to/useDebounce';
const App = (props) => {
const [state, setState] = useState({title: ''});
const debouncedTitle = useDebounce(state.title, 1000);
useEffect(() => {
// do whatever you want with state.title/debouncedTitle
}, [debouncedTitle]);
return (
// ...
);
}
// ...
答案 20 :(得分:0)
我使用这样的东西,效果很好:
let debouncer = debounce(
f => f(),
1000,
{ leading: true }, // debounce one on leading and one on trailing
);
function App(){
let [state, setState] = useState();
useEffect(() => debouncer(()=>{
// you can use state here for new state value
}),[state])
return <div />
}
答案 21 :(得分:0)
如果您在处理程序中使用它,我可以肯定这是这样做的方法。
function useThrottleScroll() {
const savedHandler = useRef();
function handleEvent() {}
useEffect(() => {
savedHandleEvent.current = handleEvent;
}, []);
const throttleOnScroll = useRef(throttle((event) => savedHandleEvent.current(event), 100)).current;
function handleEventPersistence(event) {
return throttleOnScroll(event);
}
return {
onScroll: handleEventPersistence,
};
}
答案 22 :(得分:0)
针对此用例,我写了两个简单的钩子(use-throttled-effect和use-debounced-effect),对于其他寻求简单解决方案的人来说可能很有用。
+-----+--------------------+--------------------+--------------------+-------+
| id | userid | messageid | channelid | total |
+-----+--------------------+--------------------+--------------------+-------+
| 4 | 226790622768398336 | 621662782403903489 | 446794429597220868 | 1 |
| 6 | 226790622768398336 | 621666397768122379 | 446794429597220868 | 1 |
| 9 | 276500077248512010 | 621669704653733889 | 446794429597220868 | 1 |
| 10 | 276500077248512010 | 621669842575032341 | 446794429597220868 | 1 |
+-----+--------------------+--------------------+--------------------+-------+