react-native - 通过传递一个空数组作为第二个参数,使用“useEffect”钩子只运行一次代码,但是 ESLint 抱怨空数组
问题描述
我正在 Visual Studio Code IDE 上开发一个 react-native 项目。
出于某种原因,我的 Visual Studio Code 开始自动填充代码以解决 lint 错误。
例如,我使用useEffect
hook 只运行一次代码(所以我需要传递一个空数组作为 的第二个参数useEffect
)。代码如下:
useEffect(() => {
...
// imaging my code here has 'foo', 'bar', etc variables
...
...
return () => {
console.log('Screen did unmount');
};
}, []); // ESLint complains the empty array.
ESLint 在我输入上面的代码后立即抱怨空数组:
React Hook useEffect has missing dependencies: 'foo', 'bar'. Either include them or remove the dependency array.eslint(react-hooks/exhaustive-deps)
如果我现在 ctrl+s 来保存我的代码。Visual Studio 自动将代码添加到空数组中:
useEffect(() => {
...
// imaging my code here has 'foo', 'bar', etc variables
...
...
return () => {
console.log('Screen did unmount');
};
}, [foo, bar]);
我的两个问题:
根据
useEffect
钩子的工作方式,为了只运行一次代码,我必须传递一个空数组。为什么 ESLint 会抱怨这个?useEffect
如果不推荐我的代码,那么让代码只运行一次的正确方法是什么?如何让我的 Visual Studio Code 停止自动添加代码来解决 ESLint 错误?
解决方案
我为此建议了两种方法。
您可以// eslint-disable-next-line
在您的代码中使用
useEffect(() => {
...
// imaging my code here has 'foo', 'bar', etc variables
...
...
return () => {
console.log('Screen did unmount');
};
// eslint-disable-next-line
}, [])
或者您可以删除编辑 Visual Studio 代码的 eslint 设置。
干杯。
推荐阅读
- scheme - 添加括号更改条件评估
- java - 根据十进制度数位置计算仪表偏移
- elasticsearch - 是否可以在不将其加载到索引的情况下检查特定数据是否与查询匹配?
- javascript - 为什么 scrollIntoView() 不能正常工作?
- c++ - C++11:如何访问派生类中的基类成员?
- solr - Solr 索引中的 Jackrabbit Oak Binary 属性值不正确
- django - Django - 从两个下拉菜单中选择选项并在第三个下拉菜单中显示过滤结果
- javascript - 如何在javascript中使用元键模拟逗号按键
- python - 如何减去具有多个条件的单独元组列表中的最后一个数字/元素?
- javascript - 使用 javascript 在指南上移动 SVG 对象