我正在编写一个 React 钩子,它允许我setInterval在我的组件中使用。为此,我需要在 ref 中保留最新版本的回调,以便稍后可以从间隔范围访问它。
到目前为止,这是我的代码:
import { useRef, useEffect } from 'react'
export default function useInterval(
callback: () => void,
delay: number | null,
) {
const callbackRef = useRef(callback)
// Remember the latest callback.
useEffect(() => {
callbackRef.current = callback
})
useEffect(() => {
// Don't schedule if no delay is specified.
if (delay === null) {
return
}
const id = setInterval(() => callbackRef.current(), delay)
return () => clearInterval(id)
}, [delay])
}
我的问题是关于将useEffect最新值传递给 ref的第一个实例。根据 React 文档,此代码将在我的组件呈现后执行。
我可以想象这在您将 ref 传递给元素时很有用,因此您可以确保它在呈现后具有值。但是,如果我的代码不关心组件何时呈现,那么将其保留在useEffect.
我将代码重写如下是否有意义:
import { useRef, useEffect } from 'react'
export default function useInterval(
callback: () => void,
delay: number | null,
) {
const callbackRef = useRef(callback)
// Remember the latest callback.
callbackRef.current = callback
useEffect(() => {
// Don't schedule if no delay is specified.
if (delay === null) {
return
}
const id = setInterval(() => callbackRef.current(), delay)
return () => clearInterval(id)
}, [delay])
}