[英]Why does React Linter complain about a const variable not being added to the dependency array?
If we have a function that fetches user data as such:如果我们有一个获取用户数据的 function:
const fetchUserData = () => {
/* code here */
}
And then we have a useEffect with an empty array so it runs once after the component has rendered:然后我们有一个带有空数组的 useEffect,所以它在组件渲染后运行一次:
useEffect(() => {
fetchUserData();
}, []);
Then eslint/tslint throws this warning: React Hook useEffect has a missing dependency: 'fetchUserData'. Either include it or remove the dependency array.
然后 eslint/tslint 抛出这个警告:
React Hook useEffect has a missing dependency: 'fetchUserData'. Either include it or remove the dependency array.
React Hook useEffect has a missing dependency: 'fetchUserData'. Either include it or remove the dependency array.
I get that this is good practice if say our function variable was a let
or var
but how would the fetchUserData
variable change if it's declared with a const
keyword.如果说我们的 function 变量是
let
或var
但如果使用const
关键字声明fetchUserData
变量将如何变化,我知道这是一个很好的做法。
Is this an error on the linter and we should just ignore it or is there something that I'm missing?这是 linter 上的错误,我们应该忽略它还是我遗漏了什么?
Whether the "variable"¹ referring the function is let
, var
, or const
is irrelevant.引用 function 的“变量”¹是
let
、 var
还是const
无关紧要。 Remember that every time your component needs to be rendered, your component function gets called again, which creates an entirely new execution context with its own const
(or let
or var
) "variable" with a new fetchUserData
function assigned to it.请记住,每次需要渲染您的组件时,您的组件 function 都会再次被调用,这会创建一个全新的执行上下文,其中包含自己的
const
(或let
或var
)“变量”,并分配给它的新fetchUserData
function。 useEffect
will only ever call the first one of those that's created (because you have a []
dependency array). useEffect
只会调用创建的第一个(因为你有一个[]
依赖数组)。 For this specific situation it may be harmless, but in the general case you run the risk of having closures over stale data, hence the linter warning.对于这种特定情况,它可能是无害的,但在一般情况下,您冒着关闭过时数据的风险,因此会发出 linter 警告。
If you don't use any state or props in fetchUserData
, you can relocate it inside the useEffect
callback, which both gets rid of the error and avoids recreating a function on every render that you're not going to use.如果您不使用任何 state 或
fetchUserData
中的道具,则可以将其重新定位在useEffect
回调中,这既可以消除错误,又可以避免在您不会使用的每个渲染上重新创建 function。 (If you do use state or props in fetchUserData
, it probably shouldn't only be called once when the component is mounted, but each time the state/props it uses changes.) (如果您确实使用 state 或
fetchUserData
中的道具,它可能不仅应该在安装组件时调用一次,而且每次它使用的状态/道具都会发生变化。)
¹ More generally, binding (a binding of a name to a storage slot containing a value in the lexical environment object for the execution context of the function call). ¹ 更一般地说,绑定(将名称绑定到包含词汇环境 object 中的值的存储槽,用于 function 调用的执行上下文)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.