【问题标题】:Difference between React useRef and global variable in this situation这种情况下 React useRef 和全局变量的区别
【发布时间】:2021-10-03 20:07:06
【问题描述】:

案例一:在函数组件外使用 let 变量

https://codepen.io/evan-jin/pen/VwWOPJV?editors=0010

案例2:在父函数组件中使用React.useRef

https://codepen.io/evan-jin/pen/VwWOpvg?editors=0010

案例 1

let cursorTimer = null  // << this is the point for 1 case

const Item = ({ num }) => {
    const [hoverItem, setHoverItem] = useState(null)
  
  const addCursor = useCallback(() => {
    clearTimeout(cursorTimer)
    cursorTimer = null
    
    cursorTimer = setTimeout(() => {
      document.body.style.cursor = 'wait'
    }, 10)
  }, [])
  
  const removeCursor =  useCallback(() => {
    if (cursorTimer === null) return
    
    cursorTimer = setTimeout(() => {
      document.body.style.cursor = 'grab'
    }, 500)
  }, [])
  
  useEffect(() => {
    hoverItem ? addCursor() : removeCursor()
  }, [hoverItem])

  ...

案例 2

const Item = ({ num, cursorTimerRef }) => {
    const [hoverItem, setHoverItem] = useState(null)
  
  const addCursor = useCallback(() => {
    clearTimeout(cursorTimerRef.current)
    cursorTimerRef.current = null
    
    cursorTimerRef.current = setTimeout(() => {
      document.body.style.cursor = 'wait'
    }, 10)
  }, [])
  
  const removeCursor =  useCallback(() => {
    if (cursorTimerRef.current === null) return
    
    cursorTimerRef.current = setTimeout(() => {
      document.body.style.cursor = 'grab'
    }, 500)
  }, [])
  
  useEffect(() => {
    hoverItem ? addCursor() : removeCursor()
  }, [hoverItem])

  ...

我真的很想知道相同结果之间的区别。

由于在组件外部声明和使用 'let' 变量不会触发重新渲染组件,它给我的结果与使用 React useRef 相同,它也不会触发重新渲染但可以更改组件中的状态。

我尝试在 Google 上查找和研究,但找不到适合我的问题的解决方案。不知道哪个更好用,效率更高。

有人能救我的命吗?

【问题讨论】:

    标签: javascript reactjs react-hooks settimeout


    【解决方案1】:

    它运行良好,这是意料之中的。

    从反应文档中引用 this

    避免将 refs 用于任何可以以声明方式完成的事情。

    Refs 是 React 中的一个东西,因为并非所有事情都可以通过声明方式解决。你在这里所拥有的不能以声明的方式完成。所以你必须使用参考。使用全局变量可以做到这一点,很好,但我建议使用 refs,因为它们提供了一种更简单、更 React-y 的做事方式。

    此外,全局变量会迅速污染并导致应用程序中的内存泄漏,而使用 refs 显然不是这种情况。

    【讨论】:

    • 你的回答太棒了,真的很有帮助!所以我可能会使用 Ref :) 我不知道全局变量会以某种方式导致内存泄漏。我可能会尝试研究一下。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多