英文:
How can I access the last values of states within a hook that provides debouncing functionality in React?
问题
我有一个提供函数防抖功能的钩子。但是我无法访问其中的状态的最后值。如果我添加到依赖项中,它将破坏函数防抖的结构。我该怎么办?
const debouncedCreate = useRef(
debounce(async (data) => {
try {
...
const result = await dispatch(createMachineGroup(data)).unwrap();
...
} catch (error) {
...
// memoizedMachineGroupsErrorIndicator 正在获取状态错误的最后值。
// 它在 debounce 函数外部工作。
// 但在内部,在函数防抖之前获取最后值。
if (isset(() => memoizedMachineGroupsErrorIndicator)) {
...
}
}
}, 300),
).current;
英文:
I have got a hook that provides debouncing the functions. But I can't access the last values of States in it. If I add to dependencies, It will break debouncing structure. What should I do ?
const debouncedCreate = useRef(
debounce(async (data) => {
try {
...
const result = await dispatch(createMachineGroup(data)).unwrap();
...
} catch (error) {
...
// memoizedMachineGroupsErrorIndicator is fetching last value of state errors.
// it is working outside of debounce func.
// but inside, it fetchs last value before debounced function.
if (isset(() => memoizedMachineGroupsErrorIndicator)) {
...
}
}
}, 300),
).current;
答案1
得分: 1
这是您提供的代码段的翻译:
有一个useRef
技巧可以使用。
const stateRef = useRef()
stateRef.current = memoizedMachineGroupsErrorIndicator
const debouncedCreate = useRef(
debounce(async (data) => {
try {
...
const result = await dispatch(createMachineGroup(data)).unwrap();
...
} catch (error) {
...
if (isset(() => stateRef.current)) { // 这里始终会得到最后一个值
...
}
}
}, 300),
).current;
回调函数会对stateRef
的引用进行记忆化。它的引用始终不变。只是current
属性会更改其值。
英文:
There is a useRef
trick you can use.
const stateRef = useRef()
stateRef.current = memoizedMachineGroupsErrorIndicator
const debouncedCreate = useRef(
debounce(async (data) => {
try {
...
const result = await dispatch(createMachineGroup(data)).unwrap();
...
} catch (error) {
...
if (isset(() => stateRef.current)) { // here you will always get the last value
...
}
}
}, 300),
).current;
The callback memoizes the reference of stateRef
. Its reference is always same. Just the current
property changes its value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论