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

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

How can I access the last values of states within a hook that provides debouncing functionality in React?

问题

我有一个提供函数防抖功能的钩子。但是我无法访问其中的状态的最后值。如果我添加到依赖项中,它将破坏函数防抖的结构。我该怎么办?

  1. const debouncedCreate = useRef(
  2. debounce(async (data) => {
  3. try {
  4. ...
  5. const result = await dispatch(createMachineGroup(data)).unwrap();
  6. ...
  7. } catch (error) {
  8. ...
  9. // memoizedMachineGroupsErrorIndicator 正在获取状态错误的最后值。
  10. // 它在 debounce 函数外部工作。
  11. // 但在内部,在函数防抖之前获取最后值。
  12. if (isset(() => memoizedMachineGroupsErrorIndicator)) {
  13. ...
  14. }
  15. }
  16. }, 300),
  17. ).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 ?

  1. const debouncedCreate = useRef(
  2. debounce(async (data) => {
  3. try {
  4. ...
  5. const result = await dispatch(createMachineGroup(data)).unwrap();
  6. ...
  7. } catch (error) {
  8. ...
  9. // memoizedMachineGroupsErrorIndicator is fetching last value of state errors.
  10. // it is working outside of debounce func.
  11. // but inside, it fetchs last value before debounced function.
  12. if (isset(() => memoizedMachineGroupsErrorIndicator)) {
  13. ...
  14. }
  15. }
  16. }, 300),
  17. ).current;

答案1

得分: 1

这是您提供的代码段的翻译:

有一个useRef技巧可以使用。

  1. const stateRef = useRef()
  2. stateRef.current = memoizedMachineGroupsErrorIndicator
  3. const debouncedCreate = useRef(
  4. debounce(async (data) => {
  5. try {
  6. ...
  7. const result = await dispatch(createMachineGroup(data)).unwrap();
  8. ...
  9. } catch (error) {
  10. ...
  11. if (isset(() => stateRef.current)) { // 这里始终会得到最后一个值
  12. ...
  13. }
  14. }
  15. }, 300),
  16. ).current;

回调函数会对stateRef的引用进行记忆化。它的引用始终不变。只是current属性会更改其值。

英文:

There is a useRef trick you can use.

  1. const stateRef = useRef()
  2. stateRef.current = memoizedMachineGroupsErrorIndicator
  3. const debouncedCreate = useRef(
  4. debounce(async (data) => {
  5. try {
  6. ...
  7. const result = await dispatch(createMachineGroup(data)).unwrap();
  8. ...
  9. } catch (error) {
  10. ...
  11. if (isset(() => stateRef.current)) { // here you will always get the last value
  12. ...
  13. }
  14. }
  15. }, 300),
  16. ).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:

确定