简体   繁体   English

为什么 ESLint 对使用的未使用变量发出警告?

[英]Why is ESLint throwing warning about unused variable that's used?

I've been writing React & ES6 code for about 2 months now.我已经编写 React 和 ES6 代码大约 2 个月了。 Not sure if I just haven't ran into this problem, or if I'm having a brain freeze this morning.不知道是我没有遇到这个问题,还是今天早上我的大脑冻结了。

Did some research and ran into a bunch of articles on const & let but nothing address this.做了一些研究并遇到了一堆关于const & let的文章,但没有解决这个问题。 I've been reading that you don't need to use var anymore, so then how would you handle this situation?我一直在读到您不再需要使用var了,那么您将如何处理这种情况?

function () {
  let variable = null;

  if (condition) {
    variable = 'hello world';
  }

  console.log(variable); // want 'hello world' if condition
}

Edit: please assume function is being called & condition is true .编辑:请假设正在调用函数且条件为true

I see the code works under these conditions but my confusion is this: before I referenced the variable in the console log, my ESlint reports [eslint]: 'variable' is assigned a value but never used .我看到代码在这些条件下工作,但我的困惑是:在我引用控制台日志中的变量之前,我的 ESlint 报告[eslint]: 'variable' is assigned a value but never used

Isn't it being used?不是被利用了吗?

By "using it", ESLint is referring to actually putting it to some use.通过“使用它”,ESLint 指的是实际使用它。 Simply putting a value in it does not constitute using it, as far as ESLint is concerned.就 ESLint 而言,简单地将值放入其中并不构成使用它。

A variable whose value is never accessed serves no purpose.从不访问其值的变量没有任何用途。

so its an eslint rule: https://eslint.org/docs/rules/no-unused-vars所以它的 eslint 规则: https ://eslint.org/docs/rules/no-unused-vars

if you are not familiar with what does eslint do:如果你不熟悉 eslint 做什么:

Its goal is to provide a pluggable linting utility for JavaScript它的目标是为 JavaScript 提供可插入的 linting 实用程序

if you think you wanna remove this rule you can add this line to .eslintrc如果您认为要删除此规则,可以将此行添加到 .eslintrc

nikko:cms-v3 nikko$ cat .eslintrc.json
{
  "rules": {
    ...
    "no-unused-vars": "off", // add this

Isn't it being used?不是被利用了吗?

it doesnt matter if function is called or not, if eslint sees you define a variable in that scope but you never used the variable, it will spit that error.函数是否被调用并不重要,如果 eslint 看到你在该范围内定义了一个变量,但你从未使用过该变量,它会吐出那个错误。 What you did was re-defining the variable not using it.你所做的是重新定义不使用它的变量。

let variable needs to be somehow consumed by some process let variable需要以某种方式被某个进程消耗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM