[英]Should refs be in listed as dependencies for useEffect and such?
As I understand, the containers returned by useRef are always the same - yet referencing them in useEffect and similar functions results in eslint exhaustive-deps warning.据我了解,useRef 返回的容器总是相同的——但在 useEffect 和类似函数中引用它们会导致 eslint 详尽的deps 警告。 Is it safe to ignore the warning in this case, and what's a good way to avoid both clogging the output log with warnings, and my code with disable-line comments?
在这种情况下忽略警告是否安全,以及避免使用警告阻塞 output 日志和禁用行注释的代码的好方法是什么? Or should I just stick them into dependency list to keep eslint happy?
或者我应该将它们放入依赖列表中以保持 eslint 快乐?
When useRef
is first called it creates an object with a current
property.首次调用
useRef
时,它会创建一个具有current
属性的 object。 This object will remain the same across subsequent renders.此 object 在后续渲染中将保持不变。 Ie: the reference to this object won't change.
即:对这个 object 的引用不会改变。
https://reactjs.org/docs/hooks-reference.html#useref https://reactjs.org/docs/hooks-reference.html#useref
So it's safe to omit it from the dependencies array.所以从依赖数组中省略它是安全的。
See the code below (also available in the Sandbox link):请参阅下面的代码(也可在 Sandbox 链接中找到):
https://codesandbox.io/s/cocky-dhawan-ys267?file=/src/App.jshttps://codesandbox.io/s/cocky-dhawan-ys267?file=/src/App.js
const someRef = useRef({foo: "bar"});
let x = 1;
useEffect(() => {
console.log(someRef.current.foo);
console.log(x);
}, []); // THERE IS A WARNING HERE FOR THE "x"
eslint/exhaustive-deps
is only worrying about the x
, and not the someRef.current.foo
. eslint/exhaustive-deps
只担心x
,而不是someRef.current.foo
。
NOTE: I've just put the x
there to make sure the warnings were being triggered by eslint.注意:我刚刚把
x
放在那里以确保警告是由 eslint 触发的。
The reason behind this is that useRef
isnot related to the render cycle.这背后的原因是
useRef
与渲染周期无关。 I mean, it's not recreated, neither is automatically updated after every render, like state, props or variables created during render usually are.我的意思是,它不会重新创建,也不会在每次渲染后自动更新,例如 state,渲染期间创建的道具或变量通常是。
Are you sure you are getting this warning for useRef
?你确定你收到这个
useRef
的警告吗? See the CodeSandbox link and give it a double check.查看 CodeSandbox 链接并仔细检查。 Check how are you referencing them into the
useEffect
and also check your React and Eslint/plugin versions.检查您如何将它们引用到
useEffect
,并检查您的 React 和 Eslint/plugin 版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.