[英]React useEffect dependencies for subscribe/unsubscribe with eslint exhaustive-deps
I have a useEffect
hook that should subscribe to geolocation updates when the component appears, and then unsubscribe when the component disappears.我有一个
useEffect
钩子,它应该在组件出现时订阅地理定位更新,然后在组件消失时取消订阅。 So I pass []
as the effect dependencies since I only want this to run on mount/unmount.所以我将
[]
作为效果依赖项传递,因为我只希望它在安装/卸载时运行。
import { useWatchPosition } from "@ionic/react-hooks/geolocation"
import React, { useEffect } from "react"
function SiteMap() {
const { currentPosition, startWatch, clearWatch } = useWatchPosition()
// Subscribe/Unsubscribe to geo location on component mount/unmount.
useEffect(() => {
startWatch()
return clearWatch
}, [])
return <svg>{/* ... */}</svg>
}
Which causes eslint to warn:这导致 eslint 发出警告:
React Hook useEffect has missing dependencies:
clearWatch
andstartWatch
.React Hook useEffect 缺少依赖项:
clearWatch
和startWatch
。 Either include them or remove the dependencyarray.eslint(react-hooks/exhaustive-deps)
包含它们或删除依赖项
array.eslint(react-hooks/exhaustive-deps)
So I changed it to this:所以我把它改成了这样:
useEffect(() => {
startWatch()
return clearWatch
}, [startWatch, clearWatch])
Which causes an infinite render loop.这会导致无限渲染循环。
I'm guessing the infinite loop is caused by the @ionic/react-hooks/geolocation
library which is creating new functions every time useWatchPosition()
is called, making the dependencies look stale.我猜测无限循环是由
@ionic/react-hooks/geolocation
库引起的,它在每次调用useWatchPosition()
时useWatchPosition()
创建新函数,使依赖项看起来过时。
So should I just disable the check for this line via:所以我应该通过以下方式禁用对这一行的检查:
// eslint-disable-next-line react-hooks/exhaustive-deps
Or is there some way I'm missing to do the right thing here?或者我有什么方法可以在这里做正确的事情?
Reading the useWatchPosition
source code , you can see that the functions are not created with useCallback
, this means that they are regenerated whenever the hook is called.阅读
useWatchPosition
源代码,你可以看到函数不是用useCallback
创建的,这意味着只要调用钩子,它们就会重新生成。
You can store a reference to the functions in a ref
, and use the ref.current
to call the function:您可以在
ref
存储对函数的ref
,并使用ref.current
调用该函数:
function SiteMap() {
const { currentPosition, startWatch, clearWatch } = useWatchPosition()
const startWatchRef = useRef(startWatch)
const clearWatchRef = useRef()
useEffect(() => {
clearWatch.current = clearWatch // the updated clearWatch
})
// Subscribe/Unsubscribe to geo location on component mount/unmount.
useEffect(() => {
startWatchRef.current()
return () => clearWatchRef.current()
}, [])
return <svg>{/* ... */}</svg>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.