【发布时间】: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