You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is expected. Dependencies should only include values that participate in top-down React data flow. Such as props, state, and what you calculate from them. Ref containers are fine too (since they can be passed down).
However, it doesn’t make sense to add ref.current as a dependency. For the same reason it doesn’t make sense to add window.myVariable. When it updates, React won’t know about it, and won’t update your component.
React Hook useEffect has an unnecessary dependency: 'changedRef.current'. Either exclude it or remove the dependency array. Mutable values like 'changedRef.current' aren't valid dependencies because mutating them
doesn't re-render the component react-hooks/exhaustive-deps
Hooks
useEffect/useLayoutEffect/useMemo/useCallback
都具有依赖项,可以进行有条件执行callback。一、依赖项
1.1 什么是有效的依赖项 ?
gaearon提到:
state
,props
或则它们的计算值;props
的ref
也可以作为deps
ref.current
, 全局变量等)都不可以作为deps
。原因后面会提到。
1.2 哪些变量应该放入依赖项数组?
如果
state
,props
或则它们的计算值作为useEffect/useLayoutEffect/useMemo/useCallback
的实参函数或则在实参函数里被访问到,则需要放入依赖项数组。这里需要注意的是实参函数如果来自
state
或者props
也要写入依赖数组。不过感觉没必要啊???关于此事这里Pass a dependency array to a custom hook?还进行了讨论。
总结下来就是没必要,有些第三方库(比如use-deep-compare-effect)也没有这样做。
1.3
ref.current
可以作为依赖数项吗?上面提到
ref.current
是不可以作为依赖项的,因为ref.current
的变化是不会被跟踪的(即不会触发re-render
)。但是这样写又不报错:
原因不知~~~想必
eslint-plugin-react-hooks
很聪明,当发现changedRef.current
是否作为依赖项都无所谓时就不报错了。总之:不要把
ref.current
作为依赖项,除非必须这样做,并且你知道这没问题1.4
ref.current
作为依赖数项 !这是要打脸吗?上面明明在强调不要把
ref.current
作为依赖项。总有些场景需要吧。在use-deep-compare-effect库就用到了:
// eslint-disable-next-line react-hooks/exhaustive-deps
。什么情况下可以把
ref.current
作为依赖项呢?当
ref.current
用于缓存state
或者props
的计算值(即state
或者props
的变化能引起ref.current
变化),此时可以把ref.current
作为依赖项。本质上是间接把state
或者props
的计算值作为依赖项。二、依赖项什么时候执行?
2.1 什么时候计算依赖项表达式?
依赖项表达式在
render
阶段计算。可以看看useRef 里的demo。所以依赖项发生变化得能触发
re-render
,这也是为啥只有state
,props
或者它们的计算值才可以作为依赖项的原因。2.2 怎么比较依赖项的?
每次
re-render
时逐个比较(Object.is
)依赖数组各项和上次缓存的依赖项数组的各元素值。re-render
时依赖数组长度不能变化Object.is
函数比较的,所以对于引用类型的数据比较的是引用。2.3 深比较依赖项
使用常见比较少吧,如果遇到需要深比较,可以直接把对象的属性作为依赖项。如果真的真的需要深比较可以利用库use-deep-compare-effect。
三、Issues/Concern:
参考
The text was updated successfully, but these errors were encountered: