如何在React中提供防抖功能的钩子内访问状态的最后值?

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月22日 21:36:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定