javascript - es lint '' 被分配了一个值但从未使用过'尽管我已经使用过它

标签 javascript reactjs ecmascript-6 eslint let

我有一个如下所示的函数,其中 isformValid 被标记为 let 并在 if block 中使用它并根据条件更改其值。

validateForm(validationErrors, formData) {
        let validationRules = this.state.dynamicJourneyData[this.state.currentStepName].validationRules;
        let isFormValid = true;
        let fullErrorList = [];
        validationRules.rules.forEach((rule) => {
            let errorList = this.evaluateRule(rule, formData);
            if (errorList.length > 0) {
                fullErrorList = fullErrorList.concat(errorList);
            }
        });
        let finalErrorList = [];
        let errorKeys = [];
        fullErrorList.filter((error) => errorKeys.indexOf(error.id) < 0).forEach((error) => {
                finalErrorList.push(error);
                errorKeys.push(error.id);
        }); 
        if (finalErrorList.length > 0) {
            isFormValid = false;
            if (finalErrorList.length === 1) {
                validationErrors.messageTitle = validationErrors.messageTitle
                    .replace('@count', finalErrorList.length)
                    .replace('were', 'was')
                    .replace('errors', 'error');
            } else {
                validationErrors.messageTitle = validationErrors.messageTitle.replace('@count', finalErrorList.length);
            }
            validationErrors.messageBody = finalErrorList; /*(fullErrorList.map(error=>error.label)).toString();*/
        }
        return finalErrorList;
 }

我可以看到一个 eslint 错误,因为“isFormValid”被分配了一个值但从未使用过,尽管我在 if block 中使用了它。

最佳答案

ESLint 文档对此进行了很好的描述(https://eslint.org/docs/rules/no-unused-vars):

// Write-only variables are not considered as used.
var y = 10;
y = 5;

您向 isFormValid 写入了两次(在初始化期间和 if block 中),但存储在变量中的值从未被读取,因此触发了 linting 错误。当函数返回时,存储在局部变量中的值将被丢弃。由于该值从未被读取或返回,因此它不会改变计算结果的任何内容。看起来您的代码中根本不需要这个变量。

关于javascript - es lint '' 被分配了一个值但从未使用过'尽管我已经使用过它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129557/

相关文章:

javascript - Sharepoint 2010 JSOM getEnumerator 'The collection has not been initialized. It has not been requested...'

javascript - 使用异步调用在 for 循环中构建数组

javascript - 在页面加载时自动显示选项卡内容 - jQuery Tabs

reactjs - 如何将操作列设置为 Material ui 表 ReactJs 中的最后一列?

ecmascript-6 - JSX 支持哪些 ES6 功能?

javascript - Number.IsNaN() 比 isNaN() 更坏吗

javascript - python-selenium-点击出现的链接

javascript - react : [object Object] passed through select/option value

reactjs - Webpack 2 - 无法在字符串上创建属性 'mappings'

javascript - 替换字符串的最后一部分,javascript